Date: (Fri) Apr 22, 2016

Introduction:

Data: Source: Training: https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/CPSData.csv
New:
Time period:

Synopsis:

Based on analysis utilizing <> techniques, :

Summary of key steps & error improvement stats:

Prediction Accuracy Enhancement Options:

  • transform.data chunk:
    • derive features from multiple features
  • manage.missing.data chunk:
    • Not fill missing vars
    • Fill missing numerics with a different algorithm
    • Fill missing chars with data based on clusters

[](.png)

Potential next steps include:

  • Organization:
    • Categorize by chunk
    • Priority criteria:
      1. Ease of change
      2. Impacts report
      3. Cleans innards
      4. Bug report
  • all chunks:
    • at chunk-end rm(!glb_)
  • manage.missing.data chunk:
    • cleaner way to manage re-splitting of training vs. new entity
  • extract.features chunk:
    • Add n-grams for glbFeatsText
      • “RTextTools”, “tau”, “RWeka”, and “textcat” packages
  • fit.models chunk:
    • Classification: Plot AUC Curves for all models & highlight glbMdlSel
    • Prediction accuracy scatter graph:
    • Add tiles (raw vs. PCA)
    • Use shiny for drop-down of “important” features
    • Use plot.ly for interactive plots ?

    • Change .fit suffix of model metrics to .mdl if it’s data independent (e.g. AIC, Adj.R.Squared - is it truly data independent ?, etc.)
    • create a custom model for rpart that has minbucket as a tuning parameter
    • varImp for randomForest crashes in caret version:6.0.41 -> submit bug report

  • Probability handling for multinomials vs. desired binomial outcome
  • ROCR currently supports only evaluation of binary classification tasks (version 1.0.7)
  • extensions toward multiclass classification are scheduled for the next release

  • fit.all.training chunk:
    • myplot_prediction_classification: displays ‘x’ instead of ‘+’ when there are no prediction errors
  • Compare glb_sel_mdl vs. glb_fin_mdl:
    • varImp
    • Prediction differences (shd be minimal ?)
  • Move glb_analytics_diag_plots to mydsutils.R: (+) Easier to debug (-) Too many glb vars used
  • Add print(ggplot.petrinet(glb_analytics_pn) + coord_flip()) at the end of every major chunk
  • Parameterize glb_analytics_pn
  • Move glb_impute_missing_data to mydsutils.R: (-) Too many glb vars used; glb_<>_df reassigned
  • Do non-glm methods handle interaction terms ?
  • f-score computation for classifiers should be summation across outcomes (not just the desired one ?)
  • Add accuracy computation to glb_dmy_mdl in predict.data.new chunk
  • Why does splitting fit.data.training.all chunk into separate chunks add an overhead of ~30 secs ? It’s not rbind b/c other chunks have lower elapsed time. Is it the number of plots ?
  • Incorporate code chunks in print_sessionInfo
  • Test against
    • projects in github.com/bdanalytics
    • lectures in jhu-datascience track

Analysis:

rm(list = ls())
set.seed(12345)
options(stringsAsFactors = FALSE)
source("~/Dropbox/datascience/R/mycaret.R")
source("~/Dropbox/datascience/R/mydsutils.R")
## Loading required package: caret
## Loading required package: lattice
## Loading required package: ggplot2
source("~/Dropbox/datascience/R/mypetrinet.R")
source("~/Dropbox/datascience/R/myplclust.R")
source("~/Dropbox/datascience/R/myplot.R")
source("~/Dropbox/datascience/R/myscript.R")
source("~/Dropbox/datascience/R/mytm.R")
# Gather all package requirements here
suppressPackageStartupMessages(require(doMC))
glbCores <- 6 # of cores on machine - 2
registerDoMC(glbCores) 

suppressPackageStartupMessages(require(caret))
require(plyr)
## Loading required package: plyr
require(dplyr)
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:plyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
require(knitr)
## Loading required package: knitr
require(stringr)
## Loading required package: stringr
#source("dbgcaret.R")
#packageVersion("snow")
#require(sos); findFn("cosine", maxPages=2, sortby="MaxScore")

# Analysis control global variables
# Inputs
#   url/name = "<PathPointer>"; if url specifies a zip file, name = "<filename>"; 
#               or named collection of <PathPointer>s
#   sep = choose from c(NULL, "\t")
glbObsTrnFile <- list(url = "https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/CPSData.csv" 
    # or list(url = c(NULL, <.inp1> = "<path1>", <.inp2> = "<path2>"))
    , splitSpecs = list(method = "condition" # default when glbObsNewFile is NULL
    #                       select from c("copy", NULL ???, "condition", "sample", )
    #                      ,nRatio = 0.3 # > 0 && < 1 if method == "sample" 
    #                      ,seed = 123 # any integer or glbObsTrnPartitionSeed if method == "sample" 
                         ,condition = 'is.na(EmploymentStatus)' #; '<var> <condition_operator> <value>'
                         )
    )
 
glbObsNewFile <- NULL # default OR list(url = "<obsNewFileName>") 

glbObsDropCondition <- NULL # : default
#   enclose in single-quotes b/c condition might include double qoutes
#       use | & ; NOT || &&    
#   '<condition>' 
    # 'grepl("^First Draft Video:", glbObsAll$Headline)'
    # 'is.na(glbObsAll[, glb_rsp_var_raw])'
    # '(is.na(glbObsAll[, glb_rsp_var_raw]) & grepl("Train", glbObsAll[, glbFeatsId]))'
    # 'is.na(strptime(glbObsAll[, "Date"], glbFeatsDateTime[["Date"]]["format"], tz = glbFeatsDateTime[["Date"]]["timezone"]))'
#nrow(do.call("subset",list(glbObsAll, parse(text=paste0("!(", glbObsDropCondition, ")")))))
    
glb_obs_repartition_train_condition <- NULL # : default
#    "<condition>" 

glb_max_fitobs <- NULL # or any integer
glbObsTrnPartitionSeed <- 123 # or any integer
                         
glb_is_regression <- FALSE; glb_is_classification <- !glb_is_regression; 
    glb_is_binomial <- FALSE # or TRUE or FALSE

glb_rsp_var_raw <- "EmploymentStatus"

# for classification, the response variable has to be a factor
glb_rsp_var <- "EmploymentStatus.fctr"

# if the response factor is based on numbers/logicals e.g (0/1 OR TRUE/FALSE vs. "A"/"B"), 
#   or contains spaces (e.g. "Not in Labor Force")
#   caret predict(..., type="prob") crashes
glb_map_rsp_raw_to_var <- #NULL 
function(raw) {
#     return(raw ^ 0.5)
#     return(log(raw))
#     return(log(1 + raw))
#     return(log10(raw)) 
#     return(exp(-raw / 2))
#     ret_vals <- rep_len(NA, length(raw)); ret_vals[!is.na(raw)] <- ifelse(raw[!is.na(raw)] == 1, "Y", "N"); return(relevel(as.factor(ret_vals), ref="N"))
#     as.factor(paste0("B", raw))
    as.factor(gsub(" ", "\\.", raw))    
    }

#if glb_rsp_var_raw is numeric:
#print(summary(glbObsAll[, glb_rsp_var_raw]))
#glb_map_rsp_raw_to_var(tst <- c(NA, as.numeric(summary(glbObsAll[, glb_rsp_var_raw])))) 

#if glb_rsp_var_raw is character:
#print(table(glbObsAll[, glb_rsp_var_raw], useNA = "ifany"))
#print(table(glb_map_rsp_raw_to_var(tst <- glbObsAll[, glb_rsp_var_raw]), useNA = "ifany")) 

glb_map_rsp_var_to_raw <- #NULL 
function(var) {
#     return(var ^ 2.0)
#     return(exp(var))
#     return(10 ^ var) 
#     return(-log(var) * 2)
#     as.numeric(var)
#     levels(var)[as.numeric(var)]
    gsub("\\.", " ", levels(var)[as.numeric(var)])
#     c("<=50K", " >50K")[as.numeric(var)]
#     c(FALSE, TRUE)[as.numeric(var)]
}
#print(table(glb_map_rsp_var_to_raw(glb_map_rsp_raw_to_var(tst)), useNA = "ifany"))

if ((glb_rsp_var != glb_rsp_var_raw) && is.null(glb_map_rsp_raw_to_var))
    stop("glb_map_rsp_raw_to_var function expected")

# List info gathered for various columns
# <col_name>:   <description>; <notes>
# PeopleInHousehold: The number of people in the interviewee's household.
# Region: The census region where the interviewee lives.
# State: The state where the interviewee lives.
# MetroAreaCode: A code that identifies the metropolitan area in which the interviewee lives (missing if the interviewee does not live in a metropolitan area). The mapping from codes to names of metropolitan areas is provided in the file MetroAreaCodes.csv.
# Age: The age, in years, of the interviewee. 80 represents people aged 80-84, and 85 represents people aged 85 and higher.
# Married: The marriage status of the interviewee.
# Sex: The sex of the interviewee.
# Education: The maximum level of education obtained by the interviewee.
# Race: The race of the interviewee.
# Hispanic: Whether the interviewee is of Hispanic ethnicity.
# CountryOfBirthCode: A code identifying the country of birth of the interviewee. The mapping from codes to names of countries is provided in the file CountryCodes.csv.
# Citizenship: The United States citizenship status of the interviewee.
# EmploymentStatus: The status of employment of the interviewee.
# Industry: The industry of employment of the interviewee (only available if they are employed).

# currently does not handle more than 1 column; consider concatenating multiple columns
# If glbFeatsId == NULL, ".rownames <- as.numeric(row.names())" is the default
glbFeatsId <- NULL # choose from c(NULL : default, "<id_feat>") 
glbFeatsCategory <- NULL # choose from c(NULL : default, "<category_feat>")

# User-specified exclusions
glbFeatsExclude <- c(NULL
#   Feats that shd be excluded due to known causation by prediction variable
# , "<feat1", "<feat2>"
#   Feats that are factors with unique values (as % of nObs) > 49 (empirically derived)
#   Feats that are linear combinations (alias in glm)
#   Feature-engineering phase -> start by excluding all features except id & category & work each one in
    ,"Education","Married","MetroArea"
    ,"Industry"
    ,"MetroArea.fctr","State.fctr","Country.fctr"
    ,".pos",".pos.y",".rownames"
                    ) 
if (glb_rsp_var_raw != glb_rsp_var)
    glbFeatsExclude <- union(glbFeatsExclude, glb_rsp_var_raw)                    

glbFeatsInteractionOnly <- list()
#glbFeatsInteractionOnly[["<child_feat>"]] <- "<parent_feat>"

glbFeatsDrop <- c(NULL
                # , "<feat1>", "<feat2>"
                )

glb_map_vars <- c("MetroAreaCode", "CountryOfBirthCode")
glb_map_urls <- list();
glb_map_urls[["MetroAreaCode"]] <- "https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/MetroAreaCodes.csv"
glb_map_urls[["CountryOfBirthCode"]] <- "https://d37djvu3ytnwxt.cloudfront.net/asset-v1:MITx+15.071x_3+1T2016+type@asset+block/CountryCodes.csv"

# Derived features; Use this mechanism to cleanse data ??? Cons: Data duplication ???
glbFeatsDerive <- list();

# glbFeatsDerive[["<feat.my.sfx>"]] <- list(
#     mapfn = function(<arg1>, <arg2>) { return(function(<arg1>, <arg2>)) } 
#   , args = c("<arg1>", "<arg2>"))
#myprint_df(data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos)))
#data.frame(ImageId = mapfn(glbObsAll$.src, glbObsAll$.pos))[7045:7055, ]

    # character
glbFeatsDerive[["Education.fctr"]] <- list(
    mapfn = function(Education) { raw <- Education; raw[is.na(raw)] <- "NA.my"; return(as.factor(raw)) } 
  , args = c("Education"))
glbFeatsDerive[["Married.fctr"]] <- list(
    mapfn = function(Married) { raw <- Married; raw[is.na(raw)] <- "NA.my"; return(as.factor(raw)) } 
  , args = c("Married"))
glbFeatsDerive[["MetroArea.fctr"]] <- list(
    mapfn = function(MetroArea) { raw <- MetroArea; raw[is.na(raw)] <- "NA.my"; return(as.factor(raw)) } 
  , args = c("MetroArea"))
#     mapfn = function(Week) { return(substr(Week, 1, 10)) }
#     mapfn = function(Name) { return(sapply(Name, function(thsName) 
#                                             str_sub(unlist(str_split(thsName, ","))[1], 1, 1))) } 

#     mapfn = function(descriptor) { return(plyr::revalue(descriptor, c(
#         "ABANDONED BUILDING"  = "OTHER",
#         "**"                  = "**"
#                                           ))) }

#     mapfn = function(description) { mod_raw <- description;
    # This is here because it does not work if it's in txt_map_filename
#         mod_raw <- gsub(paste0(c("\n", "\211", "\235", "\317", "\333"), collapse = "|"), " ", mod_raw)
    # Don't parse for "." because of ".com"; use customized gsub for that text
#         mod_raw <- gsub("(\\w)(!|\\*|,|-|/)(\\w)", "\\1\\2 \\3", mod_raw);
    # Some state acrnoyms need context for separation e.g. 
    #   LA/L.A. could either be "Louisiana" or "LosAngeles"
        # modRaw <- gsub("\\bL\\.A\\.( |,|')", "LosAngeles\\1", modRaw);
    #   OK/O.K. could either be "Oklahoma" or "Okay"
#         modRaw <- gsub("\\bACA OK\\b", "ACA OKay", modRaw); 
#         modRaw <- gsub("\\bNow O\\.K\\.\\b", "Now OKay", modRaw);        
    #   PR/P.R. could either be "PuertoRico" or "Public Relations"        
        # modRaw <- gsub("\\bP\\.R\\. Campaign", "PublicRelations Campaign", modRaw);        
    #   VA/V.A. could either be "Virginia" or "VeteransAdministration"        
        # modRaw <- gsub("\\bthe V\\.A\\.\\:", "the VeteranAffairs:", modRaw);
    #   
    # Custom mods

#         return(mod_raw) }

    # numeric
# Create feature based on record position/id in data   
glbFeatsDerive[[".pos"]] <- list(
    mapfn = function(.rnorm) { return(1:length(.rnorm)) }       
    , args = c(".rnorm"))    
glbFeatsDerive[[".pos.y"]] <- list(
    mapfn = function(.rnorm) { return(1:length(.rnorm)) }       
    , args = c(".rnorm"))    

# Add logs of numerics that are not distributed normally
#   Derive & keep multiple transformations of the same feature, if normality is hard to achieve with just one transformation
#   Right skew: logp1; sqrt; ^ 1/3; logp1(logp1); log10; exp(-<feat>/constant)
# glbFeatsDerive[["WordCount.log1p"]] <- list(
#     mapfn = function(WordCount) { return(log1p(WordCount)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.root2"]] <- list(
#     mapfn = function(WordCount) { return(WordCount ^ (1/2)) } 
#   , args = c("WordCount"))
# glbFeatsDerive[["WordCount.nexp"]] <- list(
#     mapfn = function(WordCount) { return(exp(-WordCount)) } 
#   , args = c("WordCount"))
#print(summary(glbObsAll$WordCount))
#print(summary(mapfn(glbObsAll$WordCount)))
    
# If imputation shd be skipped for this feature
# glbFeatsDerive[["District.fctr"]] <- list(
#     mapfn = function(District) {
#         raw <- District;
#         ret_vals <- rep_len("NA", length(raw)); 
#         ret_vals[!is.na(raw)] <- sapply(raw[!is.na(raw)], function(elm) 
#                                         ifelse(elm < 10, "1-9", 
#                                         ifelse(elm < 20, "10-19", "20+")));
#         return(relevel(as.factor(ret_vals), ref = "NA"))
#     }       
#     , args = c("District"))    

# If imputation of missing data is not working ...
# glbFeatsDerive[["FertilityRate.nonNA"]] <- list(
#     mapfn = function(FertilityRate, Region) {
#         RegionMdn <- tapply(FertilityRate, Region, FUN = median, na.rm = TRUE)
# 
#         retVal <- FertilityRate
#         retVal[is.na(FertilityRate)] <- RegionMdn[Region[is.na(FertilityRate)]]
#         return(retVal)
#     }
#     , args = c("FertilityRate", "Region"))
    
#     mapfn = function(HOSPI.COST) { return(cut(HOSPI.COST, 5, breaks = c(0, 100000, 200000, 300000, 900000), labels = NULL)) }     
#     mapfn = function(Rasmussen)  { return(ifelse(sign(Rasmussen) >= 0, 1, 0)) } 
#     mapfn = function(startprice) { return(startprice ^ (1/2)) }       
#     mapfn = function(startprice) { return(log(startprice)) }   
#     mapfn = function(startprice) { return(exp(-startprice / 20)) }
#     mapfn = function(startprice) { return(scale(log(startprice))) }     
#     mapfn = function(startprice) { return(sign(sprice.predict.diff) * (abs(sprice.predict.diff) ^ (1/10))) }        

    # factor      
#     mapfn = function(PropR) { return(as.factor(ifelse(PropR >= 0.5, "Y", "N"))) }
#     mapfn = function(productline, description) { as.factor(gsub(" ", "", productline)) }
#     mapfn = function(purpose) { return(relevel(as.factor(purpose), ref="all_other")) }
#     mapfn = function(raw) { tfr_raw <- as.character(cut(raw, 5)); 
#                             tfr_raw[is.na(tfr_raw)] <- "NA.my";
#                             return(as.factor(tfr_raw)) }
#     mapfn = function(startprice.log10) { return(cut(startprice.log10, 3)) }
#     mapfn = function(startprice.log10) { return(cut(sprice.predict.diff, c(-1000, -100, -10, -1, 0, 1, 10, 100, 1000))) }    

#     , args = c("<arg1>"))
    
    # multiple args
#     mapfn = function(id, date) { return(paste(as.character(id), as.character(date), sep = "#")) }        
#     mapfn = function(PTS, oppPTS) { return(PTS - oppPTS) }
#     mapfn = function(startprice.log10.predict, startprice) {
#                  return(spdiff <- (10 ^ startprice.log10.predict) - startprice) } 
#     mapfn = function(productline, description) { as.factor(
#         paste(gsub(" ", "", productline), as.numeric(nchar(description) > 0), sep = "*")) }
#     mapfn = function(.src, .pos) { 
#         return(paste(.src, sprintf("%04d", 
#                                    ifelse(.src == "Train", .pos, .pos - 7049)
#                                    ), sep = "#")) }       

# # If glbObsAll is not sorted in the desired manner
#     mapfn=function(Week) { return(coredata(lag(zoo(orderBy(~Week, glbObsAll)$ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI) { return(coredata(lag(zoo(ILI), -2, na.pad=TRUE))) }
#     mapfn=function(ILI.2.lag) { return(log(ILI.2.lag)) }

# glbFeatsDerive[["<var1>"]] <- glbFeatsDerive[["<var2>"]]

# tst <- "descr.my"; args_lst <- NULL; for (arg in glbFeatsDerive[[tst]]$args) args_lst[[arg]] <- glbObsAll[, arg]; print(head(args_lst[[arg]])); print(head(drv_vals <- do.call(glbFeatsDerive[[tst]]$mapfn, args_lst))); 
# print(which_ix <- which(args_lst[[arg]] == 0.75)); print(drv_vals[which_ix]); 

glbFeatsDateTime <- list()
# Use OlsonNames() to enumerate supported time zones
# glbFeatsDateTime[["<DateTimeFeat>"]] <- 
#     c(format = "%Y-%m-%d %H:%M:%S" or "%m/%e/%y", timezone = "US/Eastern", impute.na = TRUE, 
#       last.ctg = FALSE, poly.ctg = FALSE)

glbFeatsPrice <- NULL # or c("<price_var>")

glbFeatsImage <- list() #list(<imageFeat> = list(patchSize = 10)) # if patchSize not specified, no patch computation

glbFeatsText <- list()
Sys.setlocale("LC_ALL", "C") # For english
## [1] "C/C/C/C/C/en_US.UTF-8"
#glbFeatsText[["<TextFeature>"]] <- list(NULL,
#   ,names = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-screened-names>
#   ))))
#   ,rareWords = myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL, 
#       <comma-separated-nonSCOWL-words>
#   ))))
#)

# Text Processing Step: custom modifications not present in txt_munge -> use glbFeatsDerive
# Text Processing Step: universal modifications
glb_txt_munge_filenames_pfx <- "<projectId>_mytxt_"

# Text Processing Step: tolower
# Text Processing Step: myreplacePunctuation
# Text Processing Step: removeWords
glb_txt_stop_words <- list()
# Remember to use unstemmed words
if (length(glbFeatsText) > 0) {
    require(tm)
    require(stringr)

    glb_txt_stop_words[["<txt_var>"]] <- sort(myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
        # Remove any words from stopwords            
#         , setdiff(myreplacePunctuation(stopwords("english")), c("<keep_wrd1>", <keep_wrd2>"))
                                
        # Remove salutations
        ,"mr","mrs","dr","Rev"                                

        # Remove misc
        #,"th" # Happy [[:digit::]]+th birthday 

        # Remove terms present in Trn only or New only; search for "Partition post-stem"
        #   ,<comma-separated-terms>        

        # cor.y.train == NA
#         ,unlist(strsplit(paste(c(NULL
#           ,"<comma-separated-terms>"
#         ), collapse=",")

        # freq == 1; keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # chisq.pval high (e.g. == 1); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>

        # nzv.freqRatio high (e.g. >= glbFeatsNzvFreqMax); keep c("<comma-separated-terms-to-keep>")
            # ,<comma-separated-terms>        
                                            )))))
}
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^man", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 4866] > 0, c(glb_rsp_var, txtFeat)]

# To identify terms with a specific freq
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], freq == 1)$term), collapse = ",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], freq <= 2)$term), collapse = ",")
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% c("zinger"))

# To identify terms with a specific freq & 
#   are not stemmed together later OR is value of color.fctr (e.g. gold)
#paste0(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], (freq == 1) & !(term %in% c("blacked","blemish","blocked","blocks","buying","cables","careful","carefully","changed","changing","chargers","cleanly","cleared","connect","connects","connected","contains","cosmetics","default","defaulting","defective","definitely","describe","described","devices","displays","drop","drops","engravement","excellant","excellently","feels","fix","flawlessly","frame","framing","gentle","gold","guarantee","guarantees","handled","handling","having","install","iphone","iphones","keeped","keeps","known","lights","line","lining","liquid","liquidation","looking","lots","manuals","manufacture","minis","most","mostly","network","networks","noted","opening","operated","performance","performs","person","personalized","photograph","physically","placed","places","powering","pre","previously","products","protection","purchasing","returned","rotate","rotation","running","sales","second","seconds","shipped","shuts","sides","skin","skinned","sticker","storing","thats","theres","touching","unusable","update","updates","upgrade","weeks","wrapped","verified","verify") ))$term), collapse = ",")

#print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (freq <= 2)))
#glbObsAll[which(terms_mtrx[, 229] > 0), glbFeatsText]

# To identify terms with cor.y == NA
#orderBy(~-freq+term, subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y)))
#paste(sort(subset(glb_post_stop_words_terms_df_lst[[txtFeat]], is.na(cor.y))[, "term"]), collapse=",")
#orderBy(~-freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], is.na(cor.y)))

# To identify terms with low cor.y.abs
#head(orderBy(~cor.y.abs+freq+term, subset(glb_post_stem_words_terms_df_lst[[txtFeat]], !is.na(cor.y))), 5)

# To identify terms with high chisq.pval
#subset(glb_post_stem_words_terms_df_lst[[txtFeat]], chisq.pval > 0.99)
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.99) & (freq <= 10))$term), collapse=",")
#paste0(sort(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (chisq.pval > 0.9))$term), collapse=",")
#head(orderBy(~-chisq.pval+freq+term, glb_post_stem_words_terms_df_lst[[txtFeat]]), 5)
#glbObsAll[glb_post_stem_words_terms_mtrx_lst[[txtFeat]][, 68] > 0, glbFeatsText]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^m", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])

# To identify terms with high nzv.freqRatio
#summary(glb_post_stem_words_terms_df_lst[[txtFeat]]$nzv.freqRatio)
#paste0(sort(setdiff(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], (nzv.freqRatio >= glbFeatsNzvFreqMax) & (freq < 10) & (chisq.pval >= 0.05))$term, c( "128gb","3g","4g","gold","ipad1","ipad3","ipad4","ipadair2","ipadmini2","manufactur","spacegray","sprint","tmobil","verizon","wifion"))), collapse=",")

# To identify obs with a txt term
#tail(orderBy(~-freq+term, glb_post_stop_words_terms_df_lst[[txtFeat]]), 20)
#mydspObs(list(descr.my.contains="non"), cols=c("color", "carrier", "cellular", "storage"))
#grep("ever", dimnames(terms_stop_mtrx)$Terms)
#which(terms_stop_mtrx[, grep("ipad", dimnames(terms_stop_mtrx)$Terms)] > 0)
#glbObsAll[which(terms_stop_mtrx[, grep("16", dimnames(terms_stop_mtrx)$Terms)[1]] > 0), c(glbFeatsCategory, "storage", txtFeat)]

# Text Processing Step: screen for names # Move to glbFeatsText specs section in order of text processing steps
# glbFeatsText[["<txtFeat>"]]$names <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Person names for names screening
#         ,<comma-separated-list>
#         
#         # Company names
#         ,<comma-separated-list>
#                     
#         # Product names
#         ,<comma-separated-list>
#     ))))

# glbFeatsText[["<txtFeat>"]]$rareWords <- myreplacePunctuation(str_to_lower(gsub(" ", "", c(NULL
#         # Words not in SCOWL db
#         ,<comma-separated-list>
#     ))))

# To identify char vectors post glbFeatsTextMap
#grep("six(.*)hour", glb_txt_chr_lst[[txtFeat]], ignore.case = TRUE, value = TRUE)
#grep("[S|s]ix(.*)[H|h]our", glb_txt_chr_lst[[txtFeat]], value = TRUE)

# To identify whether terms shd be synonyms
#orderBy(~term, glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^moder", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ])
# term_row_df <- glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^came$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
# 
# cor(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][glbObsAll$.lcn == "Fit", term_row_df$pos], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")

# To identify which stopped words are "close" to a txt term
#sort(cluster_vars)

# Text Processing Step: stemDocument
# To identify stemmed txt terms
#glb_post_stop_words_terms_df_lst[[txtFeat]][grep("^la$", glb_post_stop_words_terms_df_lst[[txtFeat]]$term), ]
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^con", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
#glbObsAll[which(terms_stem_mtrx[, grep("use", dimnames(terms_stem_mtrx)$Terms)[[1]]] > 0), c(glbFeatsId, "productline", txtFeat)]
#glbObsAll[which(TfIdf_stem_mtrx[, 191] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#glbObsAll[which(glb_post_stop_words_terms_mtrx_lst[[txtFeat]][, 6165] > 0), c(glbFeatsId, glbFeatsCategory, txtFeat)]
#which(glbObsAll$UniqueID %in% c(11915, 11926, 12198))

# Text Processing Step: mycombineSynonyms
#   To identify which terms are associated with not -> combine "could not" & "couldn't"
#findAssocs(glb_full_DTM_lst[[txtFeat]], "not", 0.05)
#   To identify which synonyms should be combined
#orderBy(~term, glb_post_stem_words_terms_df_lst[[txtFeat]][grep("^c", glb_post_stem_words_terms_df_lst[[txtFeat]]$term), ])
chk_comb_cor <- function(syn_lst) {
#     cor(terms_stem_mtrx[glbObsAll$.src == "Train", grep("^(damag|dent|ding)$", dimnames(terms_stem_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
    print(subset(glb_post_stem_words_terms_df_lst[[txtFeat]], term %in% syn_lst$syns))
    print(subset(get_corpus_terms(tm_map(glbFeatsTextCorpus[[txtFeat]], mycombineSynonyms, list(syn_lst), lazy=FALSE)), term == syn_lst$word))
#     cor(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])], glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
#     cor(rowSums(terms_stop_mtrx[glbObsAll$.src == "Train", grep("^(damage|dent|ding)$", dimnames(terms_stop_mtrx)[[2]])]), glbObsTrn[, glb_rsp_var], use="pairwise.complete.obs")
}
#chk_comb_cor(syn_lst=list(word="cabl",  syns=c("cabl", "cord")))
#chk_comb_cor(syn_lst=list(word="damag",  syns=c("damag", "dent", "ding")))
#chk_comb_cor(syn_lst=list(word="dent",  syns=c("dent", "ding")))
#chk_comb_cor(syn_lst=list(word="use",  syns=c("use", "usag")))

glbFeatsTextSynonyms <- list()
# list parsed to collect glbFeatsText[[<txtFeat>]]$vldTerms
# glbFeatsTextSynonyms[["Hdln.my"]] <- list(NULL
#     # people in places
#     , list(word = "australia", syns = c("australia", "australian"))
#     , list(word = "italy", syns = c("italy", "Italian"))
#     , list(word = "newyork", syns = c("newyork", "newyorker"))    
#     , list(word = "Pakistan", syns = c("Pakistan", "Pakistani"))    
#     , list(word = "peru", syns = c("peru", "peruvian"))
#     , list(word = "qatar", syns = c("qatar", "qatari"))
#     , list(word = "scotland", syns = c("scotland", "scotish"))
#     , list(word = "Shanghai", syns = c("Shanghai", "Shanzhai"))    
#     , list(word = "venezuela", syns = c("venezuela", "venezuelan"))    
# 
#     # companies - needs to be data dependent 
#     #   - e.g. ensure BNP in this experiment/feat always refers to BNPParibas
#         
#     # general synonyms
#     , list(word = "Create", syns = c("Create","Creator")) 
#     , list(word = "cute", syns = c("cute","cutest"))     
#     , list(word = "Disappear", syns = c("Disappear","Fadeout"))     
#     , list(word = "teach", syns = c("teach", "taught"))     
#     , list(word = "theater",  syns = c("theater", "theatre", "theatres")) 
#     , list(word = "understand",  syns = c("understand", "understood"))    
#     , list(word = "weak",  syns = c("weak", "weaken", "weaker", "weakest"))
#     , list(word = "wealth",  syns = c("wealth", "wealthi"))    
#     
#     # custom synonyms (phrases)
#     
#     # custom synonyms (names)
#                                       )
#glbFeatsTextSynonyms[["<txtFeat>"]] <- list(NULL
#     , list(word="<stem1>",  syns=c("<stem1>", "<stem1_2>"))
#                                       )

for (txtFeat in names(glbFeatsTextSynonyms))
    for (entryIx in 1:length(glbFeatsTextSynonyms[[txtFeat]])) {
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$word)
        glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns <-
            str_to_lower(glbFeatsTextSynonyms[[txtFeat]][[entryIx]]$syns)        
    }        

glbFeatsTextSeed <- 181
# tm options include: check tm::weightSMART 
glb_txt_terms_control <- list( # Gather model performance & run-time stats
                    # weighting = function(x) weightSMART(x, spec = "nnn")
                    # weighting = function(x) weightSMART(x, spec = "lnn")
                    # weighting = function(x) weightSMART(x, spec = "ann")
                    # weighting = function(x) weightSMART(x, spec = "bnn")
                    # weighting = function(x) weightSMART(x, spec = "Lnn")
                    # 
                    weighting = function(x) weightSMART(x, spec = "ltn") # default
                    # weighting = function(x) weightSMART(x, spec = "lpn")                    
                    # 
                    # weighting = function(x) weightSMART(x, spec = "ltc")                    
                    # 
                    # weighting = weightBin 
                    # weighting = weightTf 
                    # weighting = weightTfIdf # : default
                # termFreq selection criteria across obs: tm default: list(global=c(1, Inf))
                    , bounds = list(global = c(1, Inf)) 
                # wordLengths selection criteria: tm default: c(3, Inf)
                    , wordLengths = c(1, Inf) 
                              ) 

glb_txt_cor_var <- glb_rsp_var # : default # or c(<feat>)

# select one from c("union.top.val.cor", "top.cor", "top.val", default: "top.chisq", "sparse")
glbFeatsTextFilter <- "top.chisq" 
glbFeatsTextTermsMax <- rep(10, length(glbFeatsText)) # :default
names(glbFeatsTextTermsMax) <- names(glbFeatsText)

# Text Processing Step: extractAssoc
glbFeatsTextAssocCor <- rep(1, length(glbFeatsText)) # :default 
names(glbFeatsTextAssocCor) <- names(glbFeatsText)

# Remember to use stemmed terms
glb_important_terms <- list()

# Text Processing Step: extractPatterns (ngrams)
glbFeatsTextPatterns <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- list()
#glbFeatsTextPatterns[[<txtFeat>>]] <- c(metropolitan.diary.colon = "Metropolitan Diary:")

# Have to set it even if it is not used
# Properties:
#   numrows(glb_feats_df) << numrows(glbObsFit
#   Select terms that appear in at least 0.2 * O(FP/FN(glbObsOOB)) ???
#       numrows(glbObsOOB) = 1.1 * numrows(glbObsNew) ???
glb_sprs_thresholds <- NULL # or c(<txtFeat1> = 0.988, <txtFeat2> = 0.970, <txtFeat3> = 0.970)

glbFctrMaxUniqVals <- 20 # default: 20
glb_impute_na_data <- FALSE # or TRUE
glb_mice_complete.seed <- 144 # or any integer

glb_cluster <- FALSE # : default or TRUE
glb_cluster.seed <- 189 # or any integer
glb_cluster_entropy_var <- NULL # c(glb_rsp_var, as.factor(cut(glb_rsp_var, 3)), default: NULL)
glbFeatsTextClusterVarsExclude <- FALSE # default FALSE

glb_interaction_only_feats <- NULL # : default or c(<parent_feat> = "<child_feat>")

glbFeatsNzvFreqMax <- 19 # 19 : caret default
glbFeatsNzvUniqMin <- 10 # 10 : caret default

glbRFESizes <- list()
#glbRFESizes[["mdlFamily"]] <- c(4, 8, 16, 32, 64, 67, 68, 69) # Accuracy@69/70 = 0.8258

glbObsFitOutliers <- list()
# If outliers.n >= 10; consider concatenation of interaction vars
# glbObsFitOutliers[["<mdlFamily>"]] <- c(NULL
#     is.na(.rstudent)
#     max(.rstudent)
#     is.na(.dffits)
#     .hatvalues >= 0.99        
#     -38,167,642 < minmax(.rstudent) < 49,649,823    
#     , <comma-separated-<glbFeatsId>>
#                                     )
glbObsTrnOutliers <- list()
glbObsTrnOutliers[["Final"]] <- union(glbObsFitOutliers[["All.X"]],
                                c(NULL
                                ))

# influence.measures: car::outlier; rstudent; dffits; hatvalues; dfbeta; dfbetas
#mdlId <- "All.X##rcv#glm"; obs_df <- fitobs_df
#mdlId <- "RFE.X.glm"; obs_df <- fitobs_df
#mdlId <- "Final.glm"; obs_df <- trnobs_df
#mdlId <- "CSM2.X.glm"; obs_df <- fitobs_df
#print(outliers <- car::outlierTest(glb_models_lst[[mdlId]]$finalModel))
#mdlIdFamily <- paste0(head(unlist(str_split(mdlId, "\\.")), -1), collapse="."); obs_df <- dplyr::filter_(obs_df, interp(~(!(var %in% glbObsFitOutliers[[mdlIdFamily]])), var = as.name(glbFeatsId))); model_diags_df <- cbind(obs_df, data.frame(.rstudent=stats::rstudent(glb_models_lst[[mdlId]]$finalModel)), data.frame(.dffits=stats::dffits(glb_models_lst[[mdlId]]$finalModel)), data.frame(.hatvalues=stats::hatvalues(glb_models_lst[[mdlId]]$finalModel)));print(summary(model_diags_df[, c(".rstudent",".dffits",".hatvalues")])); table(cut(model_diags_df$.hatvalues, breaks=c(0.00, 0.98, 0.99, 1.00)))

#print(subset(model_diags_df, is.na(.rstudent))[, glbFeatsId])
#print(model_diags_df[which.max(model_diags_df$.rstudent), ])
#print(subset(model_diags_df, is.na(.dffits))[, glbFeatsId])
#print(model_diags_df[which.min(model_diags_df$.dffits), ])
#print(subset(model_diags_df, .hatvalues > 0.99)[, glbFeatsId])
#dffits_df <- merge(dffits_df, outliers_df, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#dffits_df <- merge(dffits_df, glbObsFit, by="row.names", all.x=TRUE); row.names(dffits_df) <- dffits_df$Row.names; dffits_df <- subset(dffits_df, select=-Row.names)
#subset(dffits_df, !is.na(.Bonf.p))

#mdlId <- "CSM.X.glm"; vars <- myextract_actual_feats(row.names(orderBy(reformulate(c("-", paste0(mdlId, ".imp"))), myget_feats_imp(glb_models_lst[[mdlId]])))); 
#model_diags_df <- glb_get_predictions(model_diags_df, mdlId, glb_rsp_var)
#obs_ix <- row.names(model_diags_df) %in% names(outliers$rstudent)[1]
#obs_ix <- which(is.na(model_diags_df$.rstudent))
#obs_ix <- which(is.na(model_diags_df$.dffits))
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, paste0(glb_rsp_var, mdlId), vars[1:min(20, length(vars))])], obs_ix=obs_ix, id_var=glbFeatsId, category_var=glbFeatsCategory)

#model_diags_df[row.names(model_diags_df) %in% names(outliers$rstudent)[c(1:2)], ]
#ctgry_diags_df <- model_diags_df[model_diags_df[, glbFeatsCategory] %in% c("Unknown#0"), ]
#myplot_parcoord(obs_df=ctgry_diags_df[, c(glbFeatsId, glbFeatsCategory, ".rstudent", ".dffits", ".hatvalues", glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indepVar[1:20])], obs_ix=row.names(ctgry_diags_df) %in% names(outliers$rstudent)[1], id_var=glbFeatsId, category_var=glbFeatsCategory)
#table(glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), "startprice.log10.cut.fctr"])
#glbObsFit[model_diags_df[, glbFeatsCategory] %in% c("iPad1#1"), c(glbFeatsId, "startprice")]

# No outliers & .dffits == NaN
#myplot_parcoord(obs_df=model_diags_df[, c(glbFeatsId, glbFeatsCategory, glb_rsp_var, "startprice.log10.predict.RFE.X.glmnet", indepVar[1:10])], obs_ix=seq(1:nrow(model_diags_df))[is.na(model_diags_df$.dffits)], id_var=glbFeatsId, category_var=glbFeatsCategory)

# Modify mdlId to (build & extract) "<FamilyId>#<Fit|Trn>#<caretMethod>#<preProc1.preProc2>#<samplingMethod>"
glb_models_lst <- list(); glb_models_df <- data.frame()

# Add xgboost algorithm

# Regression
if (glb_is_regression) {
    glbMdlMethods <- c(NULL
        # deterministic
            #, "lm", # same as glm
            , "glm", "bayesglm", "glmnet"
            , "rpart"
        # non-deterministic
            , "gbm", "rf" 
        # Unknown
            , "nnet" , "avNNet" # runs 25 models per cv sample for tunelength=5
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
            , "bagEarth" # Takes a long time
        )
} else
# Classification - Add ada (auto feature selection)
    if (glb_is_binomial)
        glbMdlMethods <- c(NULL
        # deterministic                     
            , "bagEarth" # Takes a long time        
            , "glm", "bayesglm", "glmnet"
            , "nnet"
            , "rpart"
        # non-deterministic        
            , "gbm"
            , "avNNet" # runs 25 models per cv sample for tunelength=5      
            , "rf"
        # Unknown
            , "lda", "lda2"
                # svm models crash when predict is called -> internal to kernlab it should call predict without .outcome
            , "svmLinear", "svmLinear2"
            , "svmPoly" # runs 75 models per cv sample for tunelength=5
            , "svmRadial" 
            , "earth"
        ) else
        glbMdlMethods <- c(NULL
        # deterministic
            ,"glmnet"
        # non-deterministic 
            ,"rf"       
        # Unknown
            ,"gbm","rpart"
        )

glbMdlFamilies <- list(); glb_mdl_feats_lst <- list()
# family: Choose from c("RFE.X", "CSM.X", "All.X", "Best.Interact")
#   methods: Choose from c(NULL, <method>, glbMdlMethods) 
#glbMdlFamilies[["RFE.X"]] <- c("glmnet", "glm") # non-NULL vector is mandatory
if (glb_is_classification && !glb_is_binomial)
    # glm does not work for multinomial
    glbMdlFamilies[["All.X"]] <- c("glmnet") else    
    glbMdlFamilies[["All.X"]] <- c("glmnet", "glm")

#glbMdlFamilies[["Best.Interact"]] <- "glmnet" # non-NULL vector is mandatory

# Check if interaction features make RFE better
# glbMdlFamilies[["CSM.X"]] <- setdiff(glbMdlMethods, c("lda", "lda2")) # crashing due to category:.clusterid ??? #c("glmnet", "glm") # non-NULL list is mandatory
# glb_mdl_feats_lst[["CSM.X"]] <- c(NULL
#     , <comma-separated-features-vector>
#                                   )
# dAFeats.CSM.X %<d-% c(NULL
#     # Interaction feats up to varImp(RFE.X.glmnet) >= 50
#     , <comma-separated-features-vector>
#     , setdiff(myextract_actual_feats(predictors(rfe_fit_results)), c(NULL
#                , <comma-separated-features-vector>
#                                                                       ))    
#                                   )
# glb_mdl_feats_lst[["CSM.X"]] <- "%<d-% dAFeats.CSM.X"

glbMdlFamilies[["Final"]] <- c(NULL) # NULL vector acceptable # c("glmnet", "glm")

glbMdlAllowParallel <- list()
#glbMdlAllowParallel[["<mdlId>"]] <- FALSE
glbMdlAllowParallel[["Max.cor.Y##rcv#rpart"]] <- FALSE
glbMdlAllowParallel[["All.X##rcv#glmnet"]] <- FALSE
glbMdlAllowParallel[["All.X##rcv#glm"]] <- FALSE
glbMdlAllowParallel[["Final.All.X##rcv#glmnet"]] <- FALSE
glbMdlAllowParallel[["Final.X##rcv#glmnet"]] <- FALSE
glbMdlAllowParallel[["Final##rcv#glmnet"]] <- FALSE

# Check if tuning parameters make fit better; make it mdlFamily customizable ?
glbMdlTuneParams <- data.frame()
# When glmnet crashes at model$grid with error: ???
glmnetTuneParams <- rbind(data.frame()
                        ,data.frame(parameter = "alpha",  vals = "0.100 0.325 0.550 0.775 1.000")
                        ,data.frame(parameter = "lambda", vals = "9.342e-02")    
                        )
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams,
#                                cbind(data.frame(mdlId = "<mdlId>"),
#                                      glmnetTuneParams))

    #avNNet    
    #   size=[1] 3 5 7 9; decay=[0] 1e-04 0.001  0.01   0.1; bag=[FALSE]; RMSE=1.3300906 

    #bagEarth
    #   degree=1 [2] 3; nprune=64 128 256 512 [1024]; RMSE=0.6486663 (up)
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "bagEarth", parameter = "nprune", vals = "256")
#     ,data.frame(method = "bagEarth", parameter = "degree", vals = "2")    
# ))

    #earth 
    #   degree=[1]; nprune=2  [9] 17 25 33; RMSE=0.1334478
    
    #gbm 
    #   shrinkage=0.05 [0.10] 0.15 0.20 0.25; n.trees=100 150 200 [250] 300; interaction.depth=[1] 2 3 4 5; n.minobsinnode=[10]; RMSE=0.2008313     
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "gbm", parameter = "shrinkage", min = 0.05, max = 0.25, by = 0.05)
#     ,data.frame(method = "gbm", parameter = "n.trees", min = 100, max = 300, by = 50)
#     ,data.frame(method = "gbm", parameter = "interaction.depth", min = 1, max = 5, by = 1)
#     ,data.frame(method = "gbm", parameter = "n.minobsinnode", min = 10, max = 10, by = 10)
#     #seq(from=0.05,  to=0.25, by=0.05)
# ))

    #glmnet
    #   alpha=0.100 [0.325] 0.550 0.775 1.000; lambda=0.0005232693 0.0024288010 0.0112734954 [0.0523269304] 0.2428800957; RMSE=0.6164891
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "glmnet", parameter = "alpha", vals = "0.550 0.775 0.8875 0.94375 1.000")
#     ,data.frame(method = "glmnet", parameter = "lambda", vals = "9.858855e-05 0.0001971771 0.0009152152 0.0042480525 0.0197177130")    
# ))

    #nnet    
    #   size=3 5 [7] 9 11; decay=0.0001 0.001 0.01 [0.1] 0.2; RMSE=0.9287422
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "nnet", parameter = "size", vals = "3 5 7 9 11")
#     ,data.frame(method = "nnet", parameter = "decay", vals = "0.0001 0.0010 0.0100 0.1000 0.2000")    
# ))

    #rf # Don't bother; results are not deterministic
    #       mtry=2  35  68 [101] 134; RMSE=0.1339974
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "rf", parameter = "mtry", vals = "2 5 9 13 17")
# ))

    #rpart 
    #   cp=0.020 [0.025] 0.030 0.035 0.040; RMSE=0.1770237
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()    
#     ,data.frame(method = "rpart", parameter = "cp", vals = "0.004347826 0.008695652 0.017391304 0.021739130 0.034782609")
# ))
    
    #svmLinear
    #   C=0.01 0.05 [0.10] 0.50 1.00 2.00 3.00 4.00; RMSE=0.1271318; 0.1296718
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear", parameter = "C", vals = "0.01 0.05 0.1 0.5 1")
# ))

    #svmLinear2    
    #   cost=0.0625 0.1250 [0.25] 0.50 1.00; RMSE=0.1276354 
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method = "svmLinear2", parameter = "cost", vals = "0.0625 0.125 0.25 0.5 1")
# ))

    #svmPoly    
    #   degree=[1] 2 3 4 5; scale=0.01 0.05 [0.1] 0.5 1; C=0.50 1.00 [2.00] 3.00 4.00; RMSE=0.1276130
# glbMdlTuneParams <- myrbind_df(glbMdlTuneParams, rbind(data.frame()
#     ,data.frame(method="svmPoly", parameter="degree", min=1, max=5, by=1) #seq(1, 5, 1)
#     ,data.frame(method="svmPoly", parameter="scale", vals="0.01, 0.05, 0.1, 0.5, 1")
#     ,data.frame(method="svmPoly", parameter="C", vals="0.50, 1.00, 2.00, 3.00, 4.00")    
# ))

    #svmRadial
    #   sigma=[0.08674323]; C=0.25 0.50 1.00 [2.00] 4.00; RMSE=0.1614957
    
#glb2Sav(); all.equal(sav_models_df, glb_models_df)
    
glb_preproc_methods <- NULL
#     c("YeoJohnson", "center.scale", "range", "pca", "ica", "spatialSign")

# Baseline prediction model feature(s)
glb_Baseline_mdl_var <- NULL # or c("<feat>")

glbMdlMetric_terms <- NULL # or matrix(c(
#                               0,1,2,3,4,
#                               2,0,1,2,3,
#                               4,2,0,1,2,
#                               6,4,2,0,1,
#                               8,6,4,2,0
#                           ), byrow=TRUE, nrow=5)
glbMdlMetricSummary <- NULL # or "<metric_name>"
glbMdlMetricMaximize <- NULL # or FALSE (TRUE is not the default for both classification & regression) 
glbMdlMetricSummaryFn <- NULL # or function(data, lev=NULL, model=NULL) {
#     confusion_mtrx <- t(as.matrix(confusionMatrix(data$pred, data$obs)))
#     #print(confusion_mtrx)
#     #print(confusion_mtrx * glbMdlMetric_terms)
#     metric <- sum(confusion_mtrx * glbMdlMetric_terms) / nrow(data)
#     names(metric) <- glbMdlMetricSummary
#     return(metric)
# }

glbMdlCheckRcv <- FALSE # Turn it on when needed; otherwise takes long time
glb_rcv_n_folds <- 3 # or NULL
glb_rcv_n_repeats <- 3 # or NULL

glb_clf_proba_threshold <- NULL # 0.5

# Model selection criteria
if (glb_is_regression)
    glbMdlMetricsEval <- c("min.RMSE.OOB", "max.R.sq.OOB", "max.Adj.R.sq.fit", "min.RMSE.fit")
    #glbMdlMetricsEval <- c("min.RMSE.fit", "max.R.sq.fit", "max.Adj.R.sq.fit")    
if (glb_is_classification) {
    if (glb_is_binomial)
        glbMdlMetricsEval <- 
            c("max.Accuracy.OOB", "max.AUCROCR.OOB", "max.AUCpROC.OOB", "min.aic.fit", "max.Accuracy.fit") else        
        glbMdlMetricsEval <- c("max.Accuracy.OOB", "max.Kappa.OOB")
}

# select from NULL [no ensemble models], "auto" [all models better than MFO or Baseline], c(mdl_ids in glb_models_lst) [Typically top-rated models in auto]
glb_mdl_ensemble <- NULL
#     "%<d-% setdiff(mygetEnsembleAutoMdlIds(), 'CSM.X.rf')" 
#     c(<comma-separated-mdlIds>
#      )

# Only for classifications; for regressions remove "(.*)\\.prob" form the regex
# tmp_fitobs_df <- glbObsFit[, grep(paste0("^", gsub(".", "\\.", mygetPredictIds$value, fixed = TRUE), "CSM\\.X\\.(.*)\\.prob"), names(glbObsFit), value = TRUE)]; cor_mtrx <- cor(tmp_fitobs_df); cor_vctr <- sort(cor_mtrx[row.names(orderBy(~-Overall, varImp(glb_models_lst[["Ensemble.repeatedcv.glmnet"]])$imp))[1], ]); summary(cor_vctr); cor_vctr
#ntv.glm <- glm(reformulate(indepVar, glb_rsp_var), family = "binomial", data = glbObsFit)
#step.glm <- step(ntv.glm)

glb_sel_mdl_id <- "All.X##rcv#glmnet" #select from c(NULL, "All.X##rcv#glmnet", "RFE.X##rcv#glmnet", <mdlId>)
glb_fin_mdl_id <- NULL #select from c(NULL, glb_sel_mdl_id)

glb_dsp_cols <- c(".pos", glbFeatsId, glbFeatsCategory, glb_rsp_var
#               List critical cols excl. above
                  )

# Output specs
# lclgetfltout_df <- function(obsout_df) {
#     require(tidyr)
#     obsout_df <- obsout_df %>%
#         tidyr::separate("ImageId.x.y", c(".src", ".pos", "x", "y"), 
#                         sep = "#", remove = TRUE, extra = "merge")
#     # mnm prefix stands for max_n_mean
#     mnmout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         #dplyr::top_n(1, Probability1) %>% # Score = 3.9426         
#         #dplyr::top_n(2, Probability1) %>% # Score = ???; weighted = 3.94254;         
#         #dplyr::top_n(3, Probability1) %>% # Score = 3.9418; weighted = 3.94169; 
#         dplyr::top_n(4, Probability1) %>% # Score = ???; weighted = 3.94149;        
#         #dplyr::top_n(5, Probability1) %>% # Score = 3.9421; weighted = 3.94178
#     
#         # dplyr::summarize(xMeanN = mean(as.numeric(x)), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), Probability1), yMeanN = mean(as.numeric(y)))
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1, 0.2357323, 0.2336925)), yMeanN = mean(as.numeric(y)))    
#         # dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), yMeanN = mean(as.numeric(y)))
#         dplyr::summarize(xMeanN = weighted.mean(as.numeric(x), c(Probability1)), 
#                          yMeanN = weighted.mean(as.numeric(y), c(Probability1)))  
#     
#     maxout_df <- obsout_df %>%
#         dplyr::group_by(.pos) %>%
#         dplyr::summarize(maxProb1 = max(Probability1))
#     fltout_df <- merge(maxout_df, obsout_df, 
#                        by.x = c(".pos", "maxProb1"), by.y = c(".pos", "Probability1"),
#                        all.x = TRUE)
#     fmnout_df <- merge(fltout_df, mnmout_df, 
#                        by.x = c(".pos"), by.y = c(".pos"),
#                        all.x = TRUE)
#     return(fmnout_df)
# }
glbObsOut <- list(NULL
        # glbFeatsId will be the first output column, by default
        ,vars = list()
#         ,mapFn = function(obsout_df) {
#                   }
                  )
#obsout_df <- savobsout_df
# glbObsOut$mapFn <- function(obsout_df) {
#     txfout_df <- dplyr::select(obsout_df, -.pos.y) %>%
#         dplyr::mutate(
#             lunch     = levels(glbObsTrn[, "lunch"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "lunch"    ])), 0)],
#             dinner    = levels(glbObsTrn[, "dinner"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "dinner"   ])), 0)],
#             reserve   = levels(glbObsTrn[, "reserve"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "reserve"  ])), 0)],
#             outdoor   = levels(glbObsTrn[, "outdoor"  ])[
#                        round(mean(as.numeric(glbObsTrn[, "outdoor"  ])), 0)],
#             expensive = levels(glbObsTrn[, "expensive"])[
#                        round(mean(as.numeric(glbObsTrn[, "expensive"])), 0)],
#             liquor    = levels(glbObsTrn[, "liquor"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "liquor"   ])), 0)],
#             table     = levels(glbObsTrn[, "table"    ])[
#                        round(mean(as.numeric(glbObsTrn[, "table"    ])), 0)],
#             classy    = levels(glbObsTrn[, "classy"   ])[
#                        round(mean(as.numeric(glbObsTrn[, "classy"   ])), 0)],
#             kids      = levels(glbObsTrn[, "kids"     ])[
#                        round(mean(as.numeric(glbObsTrn[, "kids"     ])), 0)]
#                       )
#     
#     print("ObsNew output class tables:")
#     print(sapply(c("lunch","dinner","reserve","outdoor",
#                    "expensive","liquor","table",
#                    "classy","kids"), 
#                  function(feat) table(txfout_df[, feat], useNA = "ifany")))
#     
#     txfout_df <- txfout_df %>%
#         dplyr::mutate(labels = "") %>%
#         dplyr::mutate(labels = 
#     ifelse(lunch     != "-1", paste(labels, lunch    ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(dinner    != "-1", paste(labels, dinner   ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(reserve   != "-1", paste(labels, reserve  ), labels)) %>%
#         dplyr::mutate(labels = 
#     ifelse(outdoor   != "-1", paste(labels, outdoor  ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(expensive != "-1", paste(labels, expensive), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(liquor    != "-1", paste(labels, liquor   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(table     != "-1", paste(labels, table    ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(classy    != "-1", paste(labels, classy   ), labels)) %>%
#         dplyr::mutate(labels =         
#     ifelse(kids      != "-1", paste(labels, kids     ), labels)) %>%
#         dplyr::select(business_id, labels)
#     return(txfout_df)
# }
#if (!is.null(glbObsOut$mapFn)) obsout_df <- glbObsOut$mapFn(obsout_df); print(head(obsout_df))

glb_out_obs <- NULL # select from c(NULL : default to "new", "all", "new", "trn")

if (glb_is_classification && glb_is_binomial) {
    glbObsOut$vars[["Probability1"]] <- 
        "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$prob]" 
#     glbObsOut$vars[[glb_rsp_var_raw]] <- 
#         "%<d-% glb_map_rsp_var_to_raw(glbObsNew[, 
#                                             mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value])"         
} else {
#     glbObsOut$vars[[glbFeatsId]] <- 
#         "%<d-% as.integer(gsub('Test#', '', glbObsNew[, glbFeatsId]))"
    glbObsOut$vars[[glb_rsp_var]] <- 
        "%<d-% glbObsNew[, mygetPredictIds(glb_rsp_var, glb_fin_mdl_id)$value]"
#     for (outVar in setdiff(glbFeatsExcludeLcl, glb_rsp_var_raw))
#         glbObsOut$vars[[outVar]] <- 
#             paste0("%<d-% mean(glbObsAll[, \"", outVar, "\"], na.rm = TRUE)")
}    
# glbObsOut$vars[[glb_rsp_var_raw]] <- glb_rsp_var_raw
# glbObsOut$vars[[paste0(head(unlist(strsplit(mygetPredictIds$value, "")), -1), collapse = "")]] <-

glbOutStackFnames <- NULL #: default
    # c("ebayipads_txt_assoc1_out_bid1_stack.csv") # manual stack
    # c("ebayipads_finmdl_bid1_out_nnet_1.csv") # universal stack

glbOut <- list(pfx = "us_cps_2016_")
# lclImageSampleSeed <- 129
glbOutDataVizFname <- NULL # choose from c(NULL, "<projectId>_obsall.csv")


glbChunks <- list(labels = c("set_global_options_wd","set_global_options"
    ,"import.data","inspect.data","scrub.data","transform.data"
    ,"extract.features"
        ,"extract.features.datetime","extract.features.image","extract.features.price"
        ,"extract.features.text","extract.features.string"  
        ,"extract.features.end"
    ,"manage.missing.data","cluster.data","partition.data.training","select.features"
    ,"fit.models_0","fit.models_1","fit.models_2","fit.models_3"
    ,"fit.data.training_0","fit.data.training_1"
    ,"predict.data.new"         
    ,"display.session.info"))
# To ensure that all chunks in this script are in glbChunks
if (!is.null(chkChunksLabels <- knitr::all_labels()) && # knitr::all_labels() doesn't work in console runs
    !identical(chkChunksLabels, glbChunks$labels)) {
    print(sprintf("setdiff(chkChunksLabels, glbChunks$labels): %s", 
                  setdiff(chkChunksLabels, glbChunks$labels)))    
    print(sprintf("setdiff(glbChunks$labels, chkChunksLabels): %s", 
                  setdiff(glbChunks$labels, chkChunksLabels)))    
}

glbChunks[["first"]] <- NULL #default: script will load envir from previous chunk
glbChunks[["last"]] <- NULL #"extract.features.end" #NULL #default: script will save envir at end of this chunk 
#mysavChunk(glbOut$pfx, glbChunks[["last"]])

# Inspect max OOB FP
#chkObsOOB <- subset(glbObsOOB, !label.fctr.All.X..rcv.glmnet.is.acc)
#chkObsOOBFP <- subset(chkObsOOB, label.fctr.All.X..rcv.glmnet == "left_eye_center") %>% dplyr::mutate(Probability1 = label.fctr.All.X..rcv.glmnet.prob) %>% select(-.src, -.pos, -x, -y) %>% lclgetfltout_df() %>% mutate(obj.distance = (((as.numeric(x) - left_eye_center_x.int) ^ 2) + ((as.numeric(y) - left_eye_center_y.int) ^ 2)) ^ 0.5) %>% dplyr::top_n(5, obj.distance) %>% dplyr::top_n(5, -patch.cor)
#
#newImgObs <- glbObsNew[(glbObsNew$ImageId == "Test#0001"), ]; print(newImgObs[which.max(newImgObs$label.fctr.Final..rcv.glmnet.prob), ])
#OOBImgObs <- glbObsOOB[(glbObsOOB$ImageId == "Train#0003"), ]; print(OOBImgObs[which.max(OOBImgObs$label.fctr.All.X..rcv.glmnet.prob), ])

#load("us_cps_2016_extract.features.end.RData", verbose = TRUE)
#mygetImage(which(glbObsAll[, glbFeatsId] == "Train#0003"), names(glbFeatsImage)[1], plot = TRUE, featHighlight = c("left_eye_center_x", "left_eye_center_y"), ovrlHighlight = c(66, 35))

# Depict process
glb_analytics_pn <- petrinet(name = "glb_analytics_pn",
                        trans_df = data.frame(id = 1:6,
    name = c("data.training.all","data.new",
           "model.selected","model.final",
           "data.training.all.prediction","data.new.prediction"),
    x=c(   -5,-5,-15,-25,-25,-35),
    y=c(   -5, 5,  0,  0, -5,  5)
                        ),
                        places_df=data.frame(id=1:4,
    name=c("bgn","fit.data.training.all","predict.data.new","end"),
    x=c(   -0,   -20,                    -30,               -40),
    y=c(    0,     0,                      0,                 0),
    M0=c(   3,     0,                      0,                 0)
                        ),
                        arcs_df = data.frame(
    begin = c("bgn","bgn","bgn",        
            "data.training.all","model.selected","fit.data.training.all",
            "fit.data.training.all","model.final",    
            "data.new","predict.data.new",
            "data.training.all.prediction","data.new.prediction"),
    end   = c("data.training.all","data.new","model.selected",
            "fit.data.training.all","fit.data.training.all","model.final",
            "data.training.all.prediction","predict.data.new",
            "predict.data.new","data.new.prediction",
            "end","end")
                        ))
#print(ggplot.petrinet(glb_analytics_pn))
print(ggplot.petrinet(glb_analytics_pn) + coord_flip())
## Loading required package: grid

glb_analytics_avl_objs <- NULL

glb_chunks_df <- myadd_chunk(NULL, "import.data")
##         label step_major step_minor label_minor   bgn end elapsed
## 1 import.data          1          0           0 9.784  NA      NA

Step 1.0: import data

chunk option: eval=

## [1] "Reading file ./data/CPSData.csv..."
## [1] "dimensions of data in ./data/CPSData.csv: 131,302 rows x 14 cols"
##   PeopleInHousehold Region   State MetroAreaCode Age       Married    Sex
## 1                 1  South Alabama         26620  85       Widowed Female
## 2                 3  South Alabama         13820  21 Never Married   Male
## 3                 3  South Alabama         13820  37 Never Married Female
## 4                 3  South Alabama         13820  18 Never Married   Male
## 5                 3  South Alabama         26620  52       Widowed Female
## 6                 3  South Alabama         26620  24 Never Married   Male
##                Education  Race Hispanic CountryOfBirthCode     Citizenship
## 1       Associate degree White        0                 57 Citizen, Native
## 2            High school Black        0                 57 Citizen, Native
## 3            High school Black        0                 57 Citizen, Native
## 4 No high school diploma Black        0                 57 Citizen, Native
## 5       Associate degree White        0                 57 Citizen, Native
## 6      Bachelor's degree White        0                 57 Citizen, Native
##     EmploymentStatus                           Industry
## 1            Retired                               <NA>
## 2         Unemployed Professional and business services
## 3           Disabled                               <NA>
## 4 Not in Labor Force                               <NA>
## 5           Employed Professional and business services
## 6           Employed    Educational and health services
##        PeopleInHousehold Region       State MetroAreaCode Age
## 4535                   7  South    Arkansas         30780   6
## 20007                  1   West    Colorado         14500  57
## 66863                  3  South Mississippi            NA  48
## 95549                  6  South    Oklahoma            NA  17
## 96594                  1   West      Oregon         38900  85
## 129953                 2   West     Wyoming            NA  54
##              Married    Sex              Education  Race Hispanic
## 4535            <NA> Female                   <NA> Black        0
## 20007       Divorced   Male        Master's degree White        0
## 66863  Never Married Female No high school diploma Black        0
## 95549  Never Married   Male No high school diploma White        0
## 96594        Widowed Female No high school diploma White        0
## 129953       Married   Male            High school White        0
##        CountryOfBirthCode     Citizenship   EmploymentStatus      Industry
## 4535                   57 Citizen, Native               <NA>          <NA>
## 20007                  57 Citizen, Native           Employed     Financial
## 66863                  57 Citizen, Native           Disabled          <NA>
## 95549                  57 Citizen, Native Not in Labor Force          <NA>
## 96594                  57 Citizen, Native            Retired          <NA>
## 129953                 57 Citizen, Native           Employed Manufacturing
##        PeopleInHousehold Region   State MetroAreaCode Age       Married
## 131297                 5   West Wyoming            NA  14          <NA>
## 131298                 5   West Wyoming            NA  17 Never Married
## 131299                 5   West Wyoming            NA  37      Divorced
## 131300                 3   West Wyoming            NA  58       Married
## 131301                 3   West Wyoming            NA  53       Married
## 131302                 3   West Wyoming            NA  14          <NA>
##           Sex              Education  Race Hispanic CountryOfBirthCode
## 131297   Male                   <NA> White        0                 57
## 131298   Male No high school diploma White        0                 57
## 131299   Male            High school White        0                 57
## 131300   Male      Bachelor's degree White        0                 57
## 131301 Female       Associate degree White        0                 57
## 131302 Female                   <NA> White        0                 57
##            Citizenship   EmploymentStatus  Industry
## 131297 Citizen, Native               <NA>      <NA>
## 131298 Citizen, Native Not in Labor Force      <NA>
## 131299 Citizen, Native           Employed    Mining
## 131300 Citizen, Native           Employed Financial
## 131301 Citizen, Native Not in Labor Force      <NA>
## 131302 Citizen, Native               <NA>      <NA>
## 'data.frame':    131302 obs. of  14 variables:
##  $ PeopleInHousehold : int  1 3 3 3 3 3 3 2 2 2 ...
##  $ Region            : chr  "South" "South" "South" "South" ...
##  $ State             : chr  "Alabama" "Alabama" "Alabama" "Alabama" ...
##  $ MetroAreaCode     : int  26620 13820 13820 13820 26620 26620 26620 33660 33660 26620 ...
##  $ Age               : int  85 21 37 18 52 24 26 71 43 52 ...
##  $ Married           : chr  "Widowed" "Never Married" "Never Married" "Never Married" ...
##  $ Sex               : chr  "Female" "Male" "Female" "Male" ...
##  $ Education         : chr  "Associate degree" "High school" "High school" "No high school diploma" ...
##  $ Race              : chr  "White" "Black" "Black" "Black" ...
##  $ Hispanic          : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ CountryOfBirthCode: int  57 57 57 57 57 57 57 57 57 57 ...
##  $ Citizenship       : chr  "Citizen, Native" "Citizen, Native" "Citizen, Native" "Citizen, Native" ...
##  $ EmploymentStatus  : chr  "Retired" "Unemployed" "Disabled" "Not in Labor Force" ...
##  $ Industry          : chr  NA "Professional and business services" NA NA ...
##  - attr(*, "comment")= chr "glbObsTrn"
## NULL
##    PeopleInHousehold Region   State MetroAreaCode Age Married    Sex
## 14                 4  South Alabama         26620   2    <NA> Female
## 15                 4  South Alabama         26620   4    <NA>   Male
## 18                 2  South Alabama         13820  13    <NA> Female
## 28                 3  South Alabama         33860   2    <NA> Female
## 35                 6  South Alabama         33860   3    <NA> Female
## 36                 6  South Alabama         33860  11    <NA> Female
##    Education  Race Hispanic CountryOfBirthCode     Citizenship
## 14      <NA> White        0                 57 Citizen, Native
## 15      <NA> White        0                 57 Citizen, Native
## 18      <NA> Black        0                 57 Citizen, Native
## 28      <NA> White        0                 57 Citizen, Native
## 35      <NA> Black        0                 57 Citizen, Native
## 36      <NA> Black        0                 57 Citizen, Native
##    EmploymentStatus Industry
## 14             <NA>     <NA>
## 15             <NA>     <NA>
## 18             <NA>     <NA>
## 28             <NA>     <NA>
## 35             <NA>     <NA>
## 36             <NA>     <NA>
##       PeopleInHousehold    Region       State MetroAreaCode Age Married
## 229                   3     South     Alabama         13820   6    <NA>
## 22928                 3 Northeast Connecticut         76450  13    <NA>
## 51143                 5     South   Louisiana         35380   2    <NA>
## 51529                 4     South   Louisiana         43340  11    <NA>
## 52960                 5 Northeast       Maine            NA   5    <NA>
## 61204                 3   Midwest    Michigan         19820   0    <NA>
##          Sex Education  Race Hispanic CountryOfBirthCode     Citizenship
## 229   Female      <NA> Black        0                 57 Citizen, Native
## 22928 Female      <NA> White        1                 57 Citizen, Native
## 51143 Female      <NA> White        0                 57 Citizen, Native
## 51529 Female      <NA> Black        0                 57 Citizen, Native
## 52960 Female      <NA> White        0                 57 Citizen, Native
## 61204   Male      <NA> White        0                 57 Citizen, Native
##       EmploymentStatus Industry
## 229               <NA>     <NA>
## 22928             <NA>     <NA>
## 51143             <NA>     <NA>
## 51529             <NA>     <NA>
## 52960             <NA>     <NA>
## 61204             <NA>     <NA>
##        PeopleInHousehold Region   State MetroAreaCode Age Married    Sex
## 131282                 5   West Wyoming            NA   4    <NA> Female
## 131283                 5   West Wyoming            NA   9    <NA> Female
## 131285                 2   West Wyoming            NA  21 Married   Male
## 131296                 5   West Wyoming            NA  10    <NA> Female
## 131297                 5   West Wyoming            NA  14    <NA>   Male
## 131302                 3   West Wyoming            NA  14    <NA> Female
##          Education  Race Hispanic CountryOfBirthCode     Citizenship
## 131282        <NA> White        0                 57 Citizen, Native
## 131283        <NA> White        0                 57 Citizen, Native
## 131285 High school White        1                 57 Citizen, Native
## 131296        <NA> White        0                 57 Citizen, Native
## 131297        <NA> White        0                 57 Citizen, Native
## 131302        <NA> White        0                 57 Citizen, Native
##        EmploymentStatus Industry
## 131282             <NA>     <NA>
## 131283             <NA>     <NA>
## 131285             <NA>     <NA>
## 131296             <NA>     <NA>
## 131297             <NA>     <NA>
## 131302             <NA>     <NA>
## 'data.frame':    25789 obs. of  14 variables:
##  $ PeopleInHousehold : int  4 4 2 3 6 6 2 4 3 3 ...
##  $ Region            : chr  "South" "South" "South" "South" ...
##  $ State             : chr  "Alabama" "Alabama" "Alabama" "Alabama" ...
##  $ MetroAreaCode     : int  26620 26620 13820 33860 33860 33860 26620 33660 13820 13820 ...
##  $ Age               : int  2 4 13 2 3 11 5 14 5 11 ...
##  $ Married           : chr  NA NA NA NA ...
##  $ Sex               : chr  "Female" "Male" "Female" "Female" ...
##  $ Education         : chr  NA NA NA NA ...
##  $ Race              : chr  "White" "White" "Black" "White" ...
##  $ Hispanic          : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ CountryOfBirthCode: int  57 57 57 57 57 57 57 57 57 57 ...
##  $ Citizenship       : chr  "Citizen, Native" "Citizen, Native" "Citizen, Native" "Citizen, Native" ...
##  $ EmploymentStatus  : chr  NA NA NA NA ...
##  $ Industry          : chr  NA NA NA NA ...
##  - attr(*, "comment")= chr "glbObsNew"
##   PeopleInHousehold Region   State MetroAreaCode Age       Married    Sex
## 1                 1  South Alabama         26620  85       Widowed Female
## 2                 3  South Alabama         13820  21 Never Married   Male
## 3                 3  South Alabama         13820  37 Never Married Female
## 4                 3  South Alabama         13820  18 Never Married   Male
## 5                 3  South Alabama         26620  52       Widowed Female
## 6                 3  South Alabama         26620  24 Never Married   Male
##                Education  Race Hispanic CountryOfBirthCode     Citizenship
## 1       Associate degree White        0                 57 Citizen, Native
## 2            High school Black        0                 57 Citizen, Native
## 3            High school Black        0                 57 Citizen, Native
## 4 No high school diploma Black        0                 57 Citizen, Native
## 5       Associate degree White        0                 57 Citizen, Native
## 6      Bachelor's degree White        0                 57 Citizen, Native
##     EmploymentStatus                           Industry
## 1            Retired                               <NA>
## 2         Unemployed Professional and business services
## 3           Disabled                               <NA>
## 4 Not in Labor Force                               <NA>
## 5           Employed Professional and business services
## 6           Employed    Educational and health services
##        PeopleInHousehold    Region         State MetroAreaCode Age
## 42850                  2   Midwest       Indiana         26900  73
## 59500                  1 Northeast Massachusetts         71650  85
## 84212                  3 Northeast      New York         35620  51
## 92491                  2   Midwest          Ohio         18140  25
## 124956                 4      West    Washington            NA  18
## 126712                 4     South West Virginia         16620  29
##              Married    Sex         Education  Race Hispanic
## 42850        Married Female       High school White        0
## 59500        Widowed Female       High school White        0
## 84212        Married   Male Bachelor's degree White        1
## 92491        Married Female Bachelor's degree White        0
## 124956 Never Married Female       High school Black        1
## 126712       Married   Male       High school White        0
##        CountryOfBirthCode     Citizenship   EmploymentStatus
## 42850                  57 Citizen, Native            Retired
## 59500                  57 Citizen, Native            Retired
## 84212                  57 Citizen, Native           Employed
## 92491                  57 Citizen, Native Not in Labor Force
## 124956                 57 Citizen, Native Not in Labor Force
## 126712                 57 Citizen, Native           Employed
##                     Industry
## 42850                   <NA>
## 59500                   <NA>
## 84212  Public administration
## 92491                   <NA>
## 124956                  <NA>
## 126712                Mining
##        PeopleInHousehold Region   State MetroAreaCode Age       Married
## 131294                 2   West Wyoming            NA  27 Never Married
## 131295                 5   West Wyoming            NA  39      Divorced
## 131298                 5   West Wyoming            NA  17 Never Married
## 131299                 5   West Wyoming            NA  37      Divorced
## 131300                 3   West Wyoming            NA  58       Married
## 131301                 3   West Wyoming            NA  53       Married
##           Sex              Education  Race Hispanic CountryOfBirthCode
## 131294   Male            High school White        0                 57
## 131295 Female       Associate degree White        0                 57
## 131298   Male No high school diploma White        0                 57
## 131299   Male            High school White        0                 57
## 131300   Male      Bachelor's degree White        0                 57
## 131301 Female       Associate degree White        0                 57
##            Citizenship   EmploymentStatus
## 131294 Citizen, Native         Unemployed
## 131295 Citizen, Native Not in Labor Force
## 131298 Citizen, Native Not in Labor Force
## 131299 Citizen, Native           Employed
## 131300 Citizen, Native           Employed
## 131301 Citizen, Native Not in Labor Force
##                                  Industry
## 131294 Professional and business services
## 131295                               <NA>
## 131298                               <NA>
## 131299                             Mining
## 131300                          Financial
## 131301                               <NA>
## 'data.frame':    105513 obs. of  14 variables:
##  $ PeopleInHousehold : int  1 3 3 3 3 3 3 2 2 2 ...
##  $ Region            : chr  "South" "South" "South" "South" ...
##  $ State             : chr  "Alabama" "Alabama" "Alabama" "Alabama" ...
##  $ MetroAreaCode     : int  26620 13820 13820 13820 26620 26620 26620 33660 33660 26620 ...
##  $ Age               : int  85 21 37 18 52 24 26 71 43 52 ...
##  $ Married           : chr  "Widowed" "Never Married" "Never Married" "Never Married" ...
##  $ Sex               : chr  "Female" "Male" "Female" "Male" ...
##  $ Education         : chr  "Associate degree" "High school" "High school" "No high school diploma" ...
##  $ Race              : chr  "White" "Black" "Black" "Black" ...
##  $ Hispanic          : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ CountryOfBirthCode: int  57 57 57 57 57 57 57 57 57 57 ...
##  $ Citizenship       : chr  "Citizen, Native" "Citizen, Native" "Citizen, Native" "Citizen, Native" ...
##  $ EmploymentStatus  : chr  "Retired" "Unemployed" "Disabled" "Not in Labor Force" ...
##  $ Industry          : chr  NA "Professional and business services" NA NA ...
## [1] "Creating new feature: Education.fctr..."
## [1] "Creating new feature: Married.fctr..."
## Warning in myderiveFeatures(glbObsAll, glbFeatsDerive): arg MetroArea not
## available yet...
## [1] "Creating new feature: .pos..."
## [1] "Creating new feature: .pos.y..."
## Warning: using .rownames as identifiers for observations
## [1] "Partition stats:"
## Loading required package: sqldf
## Loading required package: gsubfn
## Loading required package: proto
## Loading required package: RSQLite
## Loading required package: DBI
## Loading required package: tcltk
##     EmploymentStatus  .src    .n
## 1           Employed Train 61733
## 2               <NA>  Test 25789
## 3            Retired Train 18619
## 4 Not in Labor Force Train 15246
## 5           Disabled Train  5712
## 6         Unemployed Train  4203
##     EmploymentStatus  .src    .n
## 1           Employed Train 61733
## 2               <NA>  Test 25789
## 3            Retired Train 18619
## 4 Not in Labor Force Train 15246
## 5           Disabled Train  5712
## 6         Unemployed Train  4203
## Loading required package: RColorBrewer

##    .src     .n
## 1 Train 105513
## 2  Test  25789
## Loading required package: lazyeval
## Loading required package: gdata
## gdata: read.xls support for 'XLS' (Excel 97-2004) files ENABLED.
## 
## gdata: read.xls support for 'XLSX' (Excel 2007+) files ENABLED.
## 
## Attaching package: 'gdata'
## The following objects are masked from 'package:dplyr':
## 
##     combine, first, last
## The following object is masked from 'package:stats':
## 
##     nobs
## The following object is masked from 'package:utils':
## 
##     object.size
## [1] "Found 0 duplicates by all features:"
## NULL
##          label step_major step_minor label_minor    bgn   end elapsed
## 1  import.data          1          0           0  9.784 30.03  20.246
## 2 inspect.data          2          0           0 30.031    NA      NA

Step 2.0: inspect data

## Warning: Removed 25789 rows containing non-finite values (stat_count).
## Loading required package: reshape2

##       EmploymentStatus.Disabled EmploymentStatus.Employed
## Test                         NA                        NA
## Train                      5712                     61733
##       EmploymentStatus.Not in Labor Force EmploymentStatus.Retired
## Test                                   NA                       NA
## Train                               15246                    18619
##       EmploymentStatus.Unemployed EmploymentStatus.NA
## Test                           NA               25789
## Train                        4203                  NA
##       EmploymentStatus.Disabled EmploymentStatus.Employed
## Test                         NA                        NA
## Train                0.05413551                 0.5850748
##       EmploymentStatus.Not in Labor Force EmploymentStatus.Retired
## Test                                   NA                       NA
## Train                            0.144494                0.1764617
##       EmploymentStatus.Unemployed EmploymentStatus.NA
## Test                           NA                   1
## Train                  0.03983395                  NA
## [1] "numeric data missing in glbObsAll: "
## MetroAreaCode 
##         34238 
## [1] "numeric data w/ 0s in glbObsAll: "
##      Age Hispanic 
##     1283   113008 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##           Region            State          Married              Sex 
##                0                0               NA                0 
##        Education             Race      Citizenship EmploymentStatus 
##               NA                0                0               NA 
##         Industry 
##               NA
##     EmploymentStatus EmploymentStatus.fctr    .n
## 1           Employed              Employed 61733
## 2               <NA>                  <NA> 25789
## 3            Retired               Retired 18619
## 4 Not in Labor Force    Not.in.Labor.Force 15246
## 5           Disabled              Disabled  5712
## 6         Unemployed            Unemployed  4203
## Warning: Removed 1 rows containing missing values (position_stack).

##       EmploymentStatus.fctr.Disabled EmploymentStatus.fctr.Employed
## Test                              NA                             NA
## Train                           5712                          61733
##       EmploymentStatus.fctr.Not.in.Labor.Force
## Test                                        NA
## Train                                    15246
##       EmploymentStatus.fctr.Retired EmploymentStatus.fctr.Unemployed
## Test                             NA                               NA
## Train                         18619                             4203
##       EmploymentStatus.fctr.NA
## Test                     25789
## Train                       NA
##       EmploymentStatus.fctr.Disabled EmploymentStatus.fctr.Employed
## Test                              NA                             NA
## Train                     0.05413551                      0.5850748
##       EmploymentStatus.fctr.Not.in.Labor.Force
## Test                                        NA
## Train                                 0.144494
##       EmploymentStatus.fctr.Retired EmploymentStatus.fctr.Unemployed
## Test                             NA                               NA
## Train                     0.1764617                       0.03983395
##       EmploymentStatus.fctr.NA
## Test                         1
## Train                       NA
## Loading required package: caTools

## [1] "elapsed Time (secs): 22.260000"
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.
## Warning: Removed 5268 rows containing non-finite values (stat_ydensity).
## Warning: Removed 5268 rows containing non-finite values (stat_summary).
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.

## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.
## Scale for 'y' is already present. Adding another scale for 'y', which
## will replace the existing scale.

## [1] "elapsed Time (secs): 16.943000"
## [1] "elapsed Time (secs): 16.943000"
##          label step_major step_minor label_minor    bgn    end elapsed
## 2 inspect.data          2          0           0 30.031 73.211   43.18
## 3   scrub.data          2          1           1 73.211     NA      NA

Step 2.1: scrub data

## [1] "numeric data missing in glbObsAll: "
##         MetroAreaCode EmploymentStatus.fctr 
##                 34238                 25789 
## [1] "numeric data w/ 0s in glbObsAll: "
##      Age Hispanic 
##     1283   113008 
## [1] "numeric data w/ Infs in glbObsAll: "
## named integer(0)
## [1] "numeric data w/ NaNs in glbObsAll: "
## named integer(0)
## [1] "string data missing in glbObsAll: "
##           Region            State          Married              Sex 
##                0                0               NA                0 
##        Education             Race      Citizenship EmploymentStatus 
##               NA                0                0               NA 
##         Industry 
##               NA
##            label step_major step_minor label_minor    bgn    end elapsed
## 3     scrub.data          2          1           1 73.211 78.514   5.303
## 4 transform.data          2          2           2 78.514     NA      NA

Step 2.2: transform data

## [1] "Reading file ./data/MetroAreaCodes.csv..."
## [1] "dimensions of data in ./data/MetroAreaCodes.csv: 271 rows x 2 cols"
##   Code                           MetroArea
## 1  460         Appleton-Oshkosh-Neenah, WI
## 2 3000   Grand Rapids-Muskegon-Holland, MI
## 3 3160 Greenville-Spartanburg-Anderson, SC
## 4 3610                       Jamestown, NY
## 5 3720          Kalamazoo-Battle Creek, MI
## 6 6450         Portsmouth-Rochester, NH-ME
##      Code                            MetroArea
## 24  12420                Austin-Round Rock, TX
## 52  17140      Cincinnati-Middletown, OH-KY-IN
## 125 29180                        Lafayette, LA
## 130 29700                           Laredo, TX
## 142 31420                            Macon, GA
## 185 39100 Poughkeepsie-Newburgh-Middletown, NY
##      Code                            MetroArea
## 266 76750          Portland-South Portland, ME
## 267 77200 Providence-Fall River-Warwick, MA-RI
## 268 77350               Rochester-Dover, NH-ME
## 269 78100                   Springfield, MA-CT
## 270 78700                        Waterbury, CT
## 271 79600                     Worcester, MA-CT
## 'data.frame':    271 obs. of  2 variables:
##  $ Code     : int  460 3000 3160 3610 3720 6450 10420 10500 10580 10740 ...
##  $ MetroArea: chr  "Appleton-Oshkosh-Neenah, WI" "Grand Rapids-Muskegon-Holland, MI" "Greenville-Spartanburg-Anderson, SC" "Jamestown, NY" ...
##  - attr(*, "comment")= chr "map_df"
## NULL
##   MetroAreaCode                                          MetroArea    .n
## 1            NA                                               <NA> 34238
## 2         35620 New York-Northern New Jersey-Long Island, NY-NJ-PA  5409
## 3         47900       Washington-Arlington-Alexandria, DC-VA-MD-WV  4177
## 4         31100               Los Angeles-Long Beach-Santa Ana, CA  4102
## 5         37980           Philadelphia-Camden-Wilmington, PA-NJ-DE  2855
## 6         16980                Chicago-Naperville-Joliet, IN-IN-WI  2772
##     MetroAreaCode                   MetroArea  .n
## 36          17460 Cleveland-Elyria-Mentor, OH 681
## 49          31140           Louisville, KY-IN 519
## 81          12940             Baton Rouge, LA 262
## 85          12540             Bakersfield, CA 245
## 100         30460       Lexington-Fayette, KY 198
## 181         43900             Spartanburg, SC  99
##     MetroAreaCode             MetroArea .n
## 260         46660          Valdosta, GA 42
## 261         47580     Warner Robins, GA 42
## 262         14060 Bloomington-Normal IL 40
## 263         44220       Springfield, OH 34
## 264         36140        Ocean City, NJ 30
## 265         14540     Bowling Green, KY 29
## Warning: Removed 1 rows containing missing values (position_stack).

## [1] "Reading file ./data/CountryCodes.csv..."
## [1] "dimensions of data in ./data/CountryCodes.csv: 149 rows x 2 cols"
##   Code                  Country
## 1   57            United States
## 2   66                     Guam
## 3   73              Puerto Rico
## 4   78     U. S. Virgin Islands
## 5   96 Other U. S. Island Areas
## 6  100                  Albania
##    Code   Country
## 12  108   Finland
## 24  132   Romania
## 35  149  Slovakia
## 73  231  Pakistan
## 83  247   Vietnam
## 92  313 Guatemala
##     Code                Country
## 144  508                   Fiji
## 145  515            New Zealand
## 146  523                  Tonga
## 147  527                  Samoa
## 148  528 Oceania, not specified
## 149  555              Elsewhere
## 'data.frame':    149 obs. of  2 variables:
##  $ Code   : int  57 66 73 78 96 100 102 103 104 105 ...
##  $ Country: chr  "United States" "Guam" "Puerto Rico" "U. S. Virgin Islands" ...
##  - attr(*, "comment")= chr "map_df"
## NULL
##   CountryOfBirthCode       Country     .n
## 1                 57 United States 115063
## 2                303        Mexico   3921
## 3                233   Philippines    839
## 4                210         India    770
## 5                207         China    581
## 6                 73   Puerto Rico    518
##     CountryOfBirthCode   Country  .n
## 11                 301    Canada 410
## 37                 440   Nigeria  85
## 94                 226  Malaysia  20
## 140                236 Singapore   6
## 143                461  Zimbabwe   6
## 145                527     Samoa   6
##     CountryOfBirthCode          Country .n
## 156                425             <NA>  3
## 157                142 Northern Ireland  2
## 158                228             <NA>  2
## 159                453         Tanzania  2
## 160                430             <NA>  1
## 161                460             <NA>  1
## Warning: Removed 17 rows containing missing values (position_stack).

## Warning in myderiveFeatures(glbObsAll, glbFeatsDerive): Education.fctr
## already present in glbObsAll, skipping ...
## Warning in myderiveFeatures(glbObsAll, glbFeatsDerive): Married.fctr
## already present in glbObsAll, skipping ...
## [1] "Creating new feature: MetroArea.fctr..."
## Warning in myderiveFeatures(glbObsAll, glbFeatsDerive): .pos already
## present in glbObsAll, skipping ...
## Warning in myderiveFeatures(glbObsAll, glbFeatsDerive): .pos.y already
## present in glbObsAll, skipping ...
##              label step_major step_minor label_minor    bgn   end elapsed
## 4   transform.data          2          2           2 78.514 92.22  13.706
## 5 extract.features          3          0           0 92.220    NA      NA

Step 3.0: extract features

##                       label step_major step_minor label_minor    bgn
## 5          extract.features          3          0           0 92.220
## 6 extract.features.datetime          3          1           1 98.024
##      end elapsed
## 5 98.023   5.804
## 6     NA      NA

Step 3.1: extract features datetime

##                           label step_major step_minor label_minor    bgn
## 1 extract.features.datetime.bgn          1          0           0 98.051
##   end elapsed
## 1  NA      NA
##                       label step_major step_minor label_minor    bgn
## 6 extract.features.datetime          3          1           1 98.024
## 7    extract.features.image          3          2           2 98.062
##      end elapsed
## 6 98.061   0.038
## 7     NA      NA

Step 3.2: extract features image

```{r extract.features.image, cache=FALSE, echo=FALSE, fig.height=5, fig.width=5, eval=myevlChunk(glbChunks, glbOut$pfx)}

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.image.bgn          1          0           0 98.096  NA
##   elapsed
## 1      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 98.096
## 2 extract.features.image.end          2          0           0 98.117
##      end elapsed
## 1 98.117   0.021
## 2     NA      NA
##                        label step_major step_minor label_minor    bgn
## 1 extract.features.image.bgn          1          0           0 98.096
## 2 extract.features.image.end          2          0           0 98.117
##      end elapsed
## 1 98.117   0.021
## 2     NA      NA
##                    label step_major step_minor label_minor    bgn    end
## 7 extract.features.image          3          2           2 98.062 98.129
## 8 extract.features.price          3          3           3 98.129     NA
##   elapsed
## 7   0.067
## 8      NA

Step 3.3: extract features price

##                        label step_major step_minor label_minor    bgn end
## 1 extract.features.price.bgn          1          0           0 98.157  NA
##   elapsed
## 1      NA
##                    label step_major step_minor label_minor    bgn    end
## 8 extract.features.price          3          3           3 98.129 98.167
## 9  extract.features.text          3          4           4 98.168     NA
##   elapsed
## 8   0.038
## 9      NA

Step 3.4: extract features text

##                       label step_major step_minor label_minor   bgn end
## 1 extract.features.text.bgn          1          0           0 98.21  NA
##   elapsed
## 1      NA
##                      label step_major step_minor label_minor    bgn    end
## 9    extract.features.text          3          4           4 98.168 98.219
## 10 extract.features.string          3          5           5 98.220     NA
##    elapsed
## 9    0.052
## 10      NA

Step 3.5: extract features string

##                         label step_major step_minor label_minor    bgn end
## 1 extract.features.string.bgn          1          0           0 98.255  NA
##   elapsed
## 1      NA
##                                       label step_major step_minor
## 1               extract.features.string.bgn          1          0
## 2 extract.features.stringfactorize.str.vars          2          0
##   label_minor    bgn    end elapsed
## 1           0 98.255 98.267   0.012
## 2           0 98.267     NA      NA
##             Region              State            Married 
##           "Region"            "State"          "Married" 
##                Sex          Education               Race 
##              "Sex"        "Education"             "Race" 
##        Citizenship   EmploymentStatus           Industry 
##      "Citizenship" "EmploymentStatus"         "Industry" 
##               .src          MetroArea            Country 
##             ".src"        "MetroArea"          "Country"
## Warning: Creating factors of string variable: Region: # of unique values: 4
## Warning: Creating factors of string variable: State: # of unique values: 51
## Warning: Creating factors of string variable: Sex: # of unique values: 2
## Warning: Creating factors of string variable: Race: # of unique values: 6
## Warning: Creating factors of string variable: Citizenship: # of unique
## values: 3
## Warning: Creating factors of string variable: Country: # of unique values:
## 145
##                      label step_major step_minor label_minor    bgn    end
## 10 extract.features.string          3          5           5 98.220 98.567
## 11    extract.features.end          3          6           6 98.568     NA
##    elapsed
## 10   0.347
## 11      NA

Step 3.6: extract features end

## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0

##                   label step_major step_minor label_minor    bgn    end
## 11 extract.features.end          3          6           6 98.568 99.484
## 12  manage.missing.data          4          0           0 99.484     NA
##    elapsed
## 11   0.916
## 12      NA

Step 4.0: manage missing data

## [1] "numeric data missing in : "
##         MetroAreaCode EmploymentStatus.fctr          Country.fctr 
##                 34238                 25789                   176 
## [1] "numeric data w/ 0s in : "
##      Age Hispanic 
##     1283   113008 
## [1] "numeric data w/ Infs in : "
## named integer(0)
## [1] "numeric data w/ NaNs in : "
## named integer(0)
## [1] "string data missing in : "
##           Region            State          Married              Sex 
##                0                0               NA                0 
##        Education             Race      Citizenship EmploymentStatus 
##               NA                0                0               NA 
##         Industry        MetroArea          Country 
##               NA               NA               NA
## [1] "numeric data missing in : "
##         MetroAreaCode EmploymentStatus.fctr          Country.fctr 
##                 34238                 25789                   176 
## [1] "numeric data w/ 0s in : "
##      Age Hispanic 
##     1283   113008 
## [1] "numeric data w/ Infs in : "
## named integer(0)
## [1] "numeric data w/ NaNs in : "
## named integer(0)
## [1] "string data missing in : "
##           Region            State          Married              Sex 
##                0                0               NA                0 
##        Education             Race      Citizenship EmploymentStatus 
##               NA                0                0               NA 
##         Industry        MetroArea          Country 
##               NA               NA               NA
##                  label step_major step_minor label_minor     bgn     end
## 12 manage.missing.data          4          0           0  99.484 100.641
## 13        cluster.data          5          0           0 100.642      NA
##    elapsed
## 12   1.157
## 13      NA

Step 5.0: cluster data

##                      label step_major step_minor label_minor     bgn
## 13            cluster.data          5          0           0 100.642
## 14 partition.data.training          6          0           0 101.177
##        end elapsed
## 13 101.177   0.535
## 14      NA      NA

Step 6.0: partition data training

## [1] "partition.data.training chunk: setup: elapsed: 0.00 secs"
## [1] "partition.data.training chunk: strata_mtrx complete: elapsed: 0.98 secs"
## [1] "partition.data.training chunk: obs_freq_df complete: elapsed: 0.98 secs"
## Loading required package: sampling
## 
## Attaching package: 'sampling'
## The following object is masked from 'package:caret':
## 
##     cluster
## [1] "partition.data.training chunk: Fit/OOB partition complete: elapsed: 3.08 secs"
##     EmploymentStatus.Disabled EmploymentStatus.Employed
##                            NA                        NA
## Fit                      4176                     45135
## OOB                      1536                     16598
##     EmploymentStatus.Not in Labor Force EmploymentStatus.Retired
##                                      NA                       NA
## Fit                               11147                    13613
## OOB                                4099                     5006
##     EmploymentStatus.Unemployed EmploymentStatus.NA
##                              NA               25789
## Fit                        3072                  NA
## OOB                        1131                  NA
##     EmploymentStatus.Disabled EmploymentStatus.Employed
##                            NA                        NA
## Fit                0.05413323                 0.5850822
## OOB                0.05414170                 0.5850546
##     EmploymentStatus.Not in Labor Force EmploymentStatus.Retired
##                                      NA                       NA
## Fit                           0.1444979                0.1764645
## OOB                           0.1444836                0.1764540
##     EmploymentStatus.Unemployed EmploymentStatus.NA
##                              NA                   1
## Fit                  0.03982215                  NA
## OOB                  0.03986606                  NA
##   .category .n.Fit .n.OOB .n.Tst .freqRatio.Fit .freqRatio.OOB
## 1    .dummy  77143  28370  25789              1              1
##   .freqRatio.Tst
## 1              1
## [1] "glbObsAll: "
## [1] 131302     33
## [1] "glbObsTrn: "
## [1] 105513     33
## [1] "glbObsFit: "
## [1] 77143    32
## [1] "glbObsOOB: "
## [1] 28370    32
## [1] "glbObsNew: "
## [1] 25789    32
## [1] "partition.data.training chunk: teardown: elapsed: 6.15 secs"
##                      label step_major step_minor label_minor     bgn
## 14 partition.data.training          6          0           0 101.177
## 15         select.features          7          0           0 107.383
##        end elapsed
## 14 107.382   6.206
## 15      NA      NA

Step 7.0: select features

## Warning in cor(data.matrix(entity_df[, sel_feats]), y =
## as.numeric(entity_df[, : the standard deviation is zero
##                            cor.y exclude.as.feat    cor.y.abs cor.high.X
## Age                 0.2795530159               0 0.2795530159         NA
## Married.fctr        0.1232144895               0 0.1232144895         NA
## Education.fctr      0.0574822155               0 0.0574822155         NA
## Region.fctr         0.0100051406               0 0.0100051406         NA
## MetroArea.fctr      0.0019552594               1 0.0019552594         NA
## Race.fctr          -0.0008325811               0 0.0008325811         NA
## .rnorm             -0.0027647457               0 0.0027647457         NA
## MetroAreaCode      -0.0042435142               1 0.0042435142         NA
## .pos               -0.0070536951               1 0.0070536951         NA
## .pos.y             -0.0070536951               1 0.0070536951         NA
## .rownames          -0.0070989341               1 0.0070989341         NA
## State.fctr         -0.0073429705               1 0.0073429705         NA
## Country.fctr       -0.0184660650               1 0.0184660650         NA
## Citizenship.fctr   -0.0197305604               0 0.0197305604         NA
## Hispanic           -0.0202305463               0 0.0202305463         NA
## CountryOfBirthCode -0.0239141640               1 0.0239141640         NA
## Sex.fctr           -0.0616145199               0 0.0616145199         NA
## PeopleInHousehold  -0.0862747193               0 0.0862747193         NA
## .category                     NA               1           NA         NA
##                    freqRatio percentUnique zeroVar   nzv is.cor.y.abs.low
## Age                 1.089125  6.349928e-02   FALSE FALSE            FALSE
## Married.fctr        1.797322  4.738753e-03   FALSE FALSE            FALSE
## Education.fctr      1.590536  7.582004e-03   FALSE FALSE            FALSE
## Region.fctr         1.274445  3.791002e-03   FALSE FALSE            FALSE
## MetroArea.fctr      6.253270  2.511539e-01   FALSE FALSE             TRUE
## Race.fctr           7.990088  5.686503e-03   FALSE FALSE             TRUE
## .rnorm              1.000000  9.964080e+01   FALSE FALSE            FALSE
## MetroAreaCode       1.303351  2.502061e-01   FALSE FALSE            FALSE
## .pos                1.000000  1.000000e+02   FALSE FALSE            FALSE
## .pos.y              1.000000  1.000000e+02   FALSE FALSE            FALSE
## .rownames           1.000000  1.000000e+02   FALSE FALSE            FALSE
## State.fctr          1.706890  4.833528e-02   FALSE FALSE            FALSE
## Country.fctr       24.005593  1.364761e-01   FALSE  TRUE            FALSE
## Citizenship.fctr   12.901057  2.843252e-03   FALSE FALSE            FALSE
## Hispanic            7.182474  1.895501e-03   FALSE FALSE            FALSE
## CountryOfBirthCode 24.005593  1.525878e-01   FALSE  TRUE            FALSE
## Sex.fctr            1.097632  1.895501e-03   FALSE FALSE            FALSE
## PeopleInHousehold   1.820761  1.421626e-02   FALSE FALSE            FALSE
## .category           0.000000  9.477505e-04    TRUE  TRUE               NA
## Warning in myplot_scatter(plt_feats_df, "percentUnique", "freqRatio",
## colorcol_name = "nzv", : converting nzv to class:factor
## Warning: Removed 4 rows containing missing values (geom_point).

## Warning: Removed 4 rows containing missing values (geom_point).

## Warning: Removed 4 rows containing missing values (geom_point).

##                          cor.y exclude.as.feat  cor.y.abs cor.high.X
## Country.fctr       -0.01846607               1 0.01846607         NA
## CountryOfBirthCode -0.02391416               1 0.02391416         NA
## .category                   NA               1         NA         NA
##                    freqRatio percentUnique zeroVar  nzv is.cor.y.abs.low
## Country.fctr        24.00559  0.1364760740   FALSE TRUE            FALSE
## CountryOfBirthCode  24.00559  0.1525878328   FALSE TRUE            FALSE
## .category            0.00000  0.0009477505    TRUE TRUE               NA

## [1] "numeric data missing in : "
##         MetroAreaCode EmploymentStatus.fctr          Country.fctr 
##                 34238                 25789                   176 
## [1] "numeric data w/ 0s in : "
##      Age Hispanic 
##     1283   113008 
## [1] "numeric data w/ Infs in : "
## named integer(0)
## [1] "numeric data w/ NaNs in : "
## named integer(0)
## [1] "string data missing in : "
##           Region            State          Married              Sex 
##                0                0               NA                0 
##        Education             Race      Citizenship EmploymentStatus 
##               NA                0                0               NA 
##         Industry        MetroArea          Country             .lcn 
##               NA               NA               NA            25789
## [1] "glb_feats_df:"
## [1] 19 12
##                                          id exclude.as.feat rsp_var
## EmploymentStatus.fctr EmploymentStatus.fctr            TRUE    TRUE
##                                          id cor.y exclude.as.feat
## EmploymentStatus.fctr EmploymentStatus.fctr    NA            TRUE
##                       cor.y.abs cor.high.X freqRatio percentUnique zeroVar
## EmploymentStatus.fctr        NA         NA        NA            NA      NA
##                       nzv is.cor.y.abs.low interaction.feat
## EmploymentStatus.fctr  NA               NA               NA
##                       shapiro.test.p.value rsp_var_raw rsp_var
## EmploymentStatus.fctr                   NA          NA    TRUE
## [1] "glb_feats_df vs. glbObsAll: "
## character(0)
## [1] "glbObsAll vs. glb_feats_df: "
## character(0)
##              label step_major step_minor label_minor     bgn     end
## 15 select.features          7          0           0 107.383 118.503
## 16      fit.models          8          0           0 118.503      NA
##    elapsed
## 15   11.12
## 16      NA

Step 8.0: fit models

fit.models_0_chunk_df <- myadd_chunk(NULL, "fit.models_0_bgn", label.minor = "setup")
##              label step_major step_minor label_minor     bgn end elapsed
## 1 fit.models_0_bgn          1          0       setup 119.026  NA      NA
# load(paste0(glbOut$pfx, "dsk.RData"))

get_model_sel_frmla <- function() {
    model_evl_terms <- c(NULL)
    # min.aic.fit might not be avl
    lclMdlEvlCriteria <- 
        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)]
    for (metric in lclMdlEvlCriteria)
        model_evl_terms <- c(model_evl_terms, 
                             ifelse(length(grep("max", metric)) > 0, "-", "+"), metric)
    if (glb_is_classification && glb_is_binomial)
        model_evl_terms <- c(model_evl_terms, "-", "opt.prob.threshold.OOB")
    model_sel_frmla <- as.formula(paste(c("~ ", model_evl_terms), collapse = " "))
    return(model_sel_frmla)
}

get_dsp_models_df <- function() {
    dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    dsp_models_df <- 
        #orderBy(get_model_sel_frmla(), glb_models_df)[, c("id", glbMdlMetricsEval)]
        orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols]    
    nCvMdl <- sapply(glb_models_lst, function(mdl) nrow(mdl$results))
    nParams <- sapply(glb_models_lst, function(mdl) ifelse(mdl$method == "custom", 0, 
        nrow(subset(modelLookup(mdl$method), parameter != "parameter"))))
    
#     nCvMdl <- nCvMdl[names(nCvMdl) != "avNNet"]
#     nParams <- nParams[names(nParams) != "avNNet"]    
    
    if (length(cvMdlProblems <- nCvMdl[nCvMdl <= nParams]) > 0) {
        print("Cross Validation issues:")
        warning("Cross Validation issues:")        
        print(cvMdlProblems)
    }
    
    pltMdls <- setdiff(names(nCvMdl), names(cvMdlProblems))
    pltMdls <- setdiff(pltMdls, names(nParams[nParams == 0]))
    
    # length(pltMdls) == 21
    png(paste0(glbOut$pfx, "bestTune.png"), width = 480 * 2, height = 480 * 4)
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(ceiling(length(pltMdls) / 2.0), 2)))
    pltIx <- 1
    for (mdlId in pltMdls) {
        print(ggplot(glb_models_lst[[mdlId]], highBestTune = TRUE) + labs(title = mdlId),   
              vp = viewport(layout.pos.row = ceiling(pltIx / 2.0), 
                            layout.pos.col = ((pltIx - 1) %% 2) + 1))  
        pltIx <- pltIx + 1
    }
    dev.off()

    if (all(row.names(dsp_models_df) != dsp_models_df$id))
        row.names(dsp_models_df) <- dsp_models_df$id
    return(dsp_models_df)
}
#get_dsp_models_df()

if (glb_is_classification && glb_is_binomial && 
        (length(unique(glbObsFit[, glb_rsp_var])) < 2))
    stop("glbObsFit$", glb_rsp_var, ": contains less than 2 unique values: ",
         paste0(unique(glbObsFit[, glb_rsp_var]), collapse=", "))

max_cor_y_x_vars <- orderBy(~ -cor.y.abs, 
        subset(glb_feats_df, (exclude.as.feat == 0) & !nzv & !is.cor.y.abs.low & 
                                is.na(cor.high.X)))[1:2, "id"]
max_cor_y_x_vars <- max_cor_y_x_vars[!is.na(max_cor_y_x_vars)]
if (length(max_cor_y_x_vars) < 2)
    max_cor_y_x_vars <- union(max_cor_y_x_vars, ".pos")

if (!is.null(glb_Baseline_mdl_var)) {
    if ((max_cor_y_x_vars[1] != glb_Baseline_mdl_var) & 
        (glb_feats_df[glb_feats_df$id == max_cor_y_x_vars[1], "cor.y.abs"] > 
         glb_feats_df[glb_feats_df$id == glb_Baseline_mdl_var, "cor.y.abs"]))
        stop(max_cor_y_x_vars[1], " has a higher correlation with ", glb_rsp_var, 
             " than the Baseline var: ", glb_Baseline_mdl_var)
}

glb_model_type <- ifelse(glb_is_regression, "regression", "classification")
    
# Model specs
# c("id.prefix", "method", "type",
#   # trainControl params
#   "preProc.method", "cv.n.folds", "cv.n.repeats", "summary.fn",
#   # train params
#   "metric", "metric.maximize", "tune.df")

# Baseline
if (!is.null(glb_Baseline_mdl_var)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                            paste0("fit.models_0_", "Baseline"), major.inc = FALSE,
                                    label.minor = "mybaseln_classfr")
    ret_lst <- myfit_mdl(mdl_id="Baseline", 
                         model_method="mybaseln_classfr",
                        indepVar=glb_Baseline_mdl_var,
                        rsp_var=glb_rsp_var,
                        fit_df=glbObsFit, OOB_df=glbObsOOB)
}    

# Most Frequent Outcome "MFO" model: mean(y) for regression
#   Not using caret's nullModel since model stats not avl
#   Cannot use rpart for multinomial classification since it predicts non-MFO
if (glb_is_classification) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "MFO"), major.inc = FALSE,
                                        label.minor = "myMFO_classfr")

    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "MFO", type = glb_model_type, trainControl.method = "none",
        train.method = ifelse(glb_is_regression, "lm", "myMFO_classfr"))),
                            indepVar = ".rnorm", rsp_var = glb_rsp_var,
                            fit_df = glbObsFit, OOB_df = glbObsOOB)

        # "random" model - only for classification; 
        #   none needed for regression since it is same as MFO
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                                paste0("fit.models_0_", "Random"), major.inc = FALSE,
                                        label.minor = "myrandom_classfr")

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)    
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Random", type = glb_model_type, trainControl.method = "none",
        train.method = "myrandom_classfr")),
                        indepVar = ".rnorm", rsp_var = glb_rsp_var,
                        fit_df = glbObsFit, OOB_df = glbObsOOB)
}
##              label step_major step_minor   label_minor     bgn     end
## 1 fit.models_0_bgn          1          0         setup 119.026 119.059
## 2 fit.models_0_MFO          1          1 myMFO_classfr 119.059      NA
##   elapsed
## 1   0.033
## 2      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: MFO###myMFO_classfr"
## [1] "    indepVar: .rnorm"
## [1] "myfit_mdl: setup complete: 0.421000 secs"
## Fitting parameter = none on full training set
## [1] "in MFO.Classifier$fit"
## [1] "unique.vals:"
## [1] Disabled           Employed           Not.in.Labor.Force
## [4] Retired            Unemployed        
## Levels: Disabled Employed Not.in.Labor.Force Retired Unemployed
## [1] "unique.prob:"
## y
##           Employed            Retired Not.in.Labor.Force 
##         0.58508225         0.17646449         0.14449788 
##           Disabled         Unemployed 
##         0.05413323         0.03982215 
## [1] "MFO.val:"
## [1] "Employed"
## [1] "myfit_mdl: train complete: 0.995000 secs"
##             Length Class      Mode     
## unique.vals 5      factor     numeric  
## unique.prob 5      -none-     numeric  
## MFO.val     1      -none-     character
## x.names     1      -none-     character
## xNames      1      -none-     character
## problemType 1      -none-     character
## tuneValue   1      data.frame list     
## obsLevels   5      -none-     character
## [1] "myfit_mdl: train diagnostics complete: 0.997000 secs"
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     4176                  0       0
##   Employed                  0    45135                  0       0
##   Not.in.Labor.Force        0    11147                  0       0
##   Retired                   0    13613                  0       0
##   Unemployed                0     3072                  0       0
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.5850822      0.0000000      0.5815957      0.5885624      0.5850822 
## AccuracyPValue  McnemarPValue 
##      0.5015403            NaN 
## [1] "entr MFO.Classifier$predict"
## [1] "exit MFO.Classifier$predict"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     1536                  0       0
##   Employed                  0    16598                  0       0
##   Not.in.Labor.Force        0     4099                  0       0
##   Retired                   0     5006                  0       0
##   Unemployed                0     1131                  0       0
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.5850546      0.0000000      0.5792951      0.5907967      0.5850546 
## AccuracyPValue  McnemarPValue 
##      0.5025398            NaN 
## [1] "myfit_mdl: predict complete: 1.288000 secs"
##                    id  feats max.nTuningRuns min.elapsedtime.everything
## 1 MFO###myMFO_classfr .rnorm               0                      0.484
##   min.elapsedtime.final max.Accuracy.fit max.AccuracyLower.fit
## 1                  0.02        0.5850822             0.5815957
##   max.AccuracyUpper.fit max.Kappa.fit max.Accuracy.OOB
## 1             0.5885624             0        0.5850546
##   max.AccuracyLower.OOB max.AccuracyUpper.OOB max.Kappa.OOB
## 1             0.5792951             0.5907967             0
## [1] "myfit_mdl: exit: 1.293000 secs"
##                 label step_major step_minor      label_minor     bgn
## 2    fit.models_0_MFO          1          1    myMFO_classfr 119.059
## 3 fit.models_0_Random          1          2 myrandom_classfr 120.358
##       end elapsed
## 2 120.358   1.299
## 3      NA      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Random###myrandom_classfr"
## [1] "    indepVar: .rnorm"
## [1] "myfit_mdl: setup complete: 0.417000 secs"
## Fitting parameter = none on full training set
## [1] "myfit_mdl: train complete: 0.832000 secs"
##             Length Class      Mode     
## unique.vals 5      factor     numeric  
## unique.prob 5      table      numeric  
## xNames      1      -none-     character
## problemType 1      -none-     character
## tuneValue   1      data.frame list     
## obsLevels   5      -none-     character
## [1] "myfit_mdl: train diagnostics complete: 0.833000 secs"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                239     2488                605     677
##   Employed               2500    26395               6634    7851
##   Not.in.Labor.Force      566     6529               1646    1988
##   Retired                 734     7958               1929    2431
##   Unemployed              171     1732                475     574
##                     Prediction
## Reference            Unemployed
##   Disabled                  167
##   Employed                 1755
##   Not.in.Labor.Force        418
##   Retired                   561
##   Unemployed                120
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##    0.399660371    0.001664263    0.396201158    0.403127131    0.585082250 
## AccuracyPValue  McnemarPValue 
##    1.000000000    0.434626705 
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                 83      896                219     276
##   Employed                922     9745               2383    2890
##   Not.in.Labor.Force      228     2400                584     753
##   Retired                 272     2914                777     865
##   Unemployed               54      630                159     241
##                     Prediction
## Reference            Unemployed
##   Disabled                   62
##   Employed                  658
##   Not.in.Labor.Force        134
##   Retired                   178
##   Unemployed                 47
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   0.3991540360   0.0006568311   0.3934483537   0.4048803781   0.5850546352 
## AccuracyPValue  McnemarPValue 
##   1.0000000000   0.1783274495 
## [1] "myfit_mdl: predict complete: 1.115000 secs"
##                          id  feats max.nTuningRuns
## 1 Random###myrandom_classfr .rnorm               0
##   min.elapsedtime.everything min.elapsedtime.final max.Accuracy.fit
## 1                      0.336                 0.017        0.3996604
##   max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1             0.3962012             0.4031271   0.001664263
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1         0.399154             0.3934484             0.4048804
##   max.Kappa.OOB
## 1  0.0006568311
## [1] "myfit_mdl: exit: 1.121000 secs"
# Max.cor.Y
#   Check impact of cv
#       rpart is not a good candidate since caret does not optimize cp (only tuning parameter of rpart) well
fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                        paste0("fit.models_0_", "Max.cor.Y.rcv.*X*"), major.inc = FALSE,
                                    label.minor = "glmnet")
##                            label step_major step_minor      label_minor
## 3            fit.models_0_Random          1          2 myrandom_classfr
## 4 fit.models_0_Max.cor.Y.rcv.*X*          1          3           glmnet
##       bgn     end elapsed
## 3 120.358 121.487    1.13
## 4 121.488      NA      NA
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
    id.prefix = "Max.cor.Y.rcv.1X1", type = glb_model_type, trainControl.method = "none",
    train.method = "glmnet")),
                    indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y.rcv.1X1###glmnet"
## [1] "    indepVar: Age,Married.fctr"
## [1] "myfit_mdl: setup complete: 0.689000 secs"
## Loading required package: glmnet
## Loading required package: Matrix
## Loaded glmnet 2.0-5
## Fitting alpha = 0.1, lambda = 0.0047 on full training set
## [1] "myfit_mdl: train complete: 12.953000 secs"

##             Length Class      Mode     
## a0          470    -none-     numeric  
## beta          5    -none-     list     
## dfmat       470    -none-     numeric  
## df           94    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       94    -none-     numeric  
## dev.ratio    94    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    5    -none-     character
## grouped       1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames        6    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     5    -none-     character
## [1] "min lambda > lambdaOpt:"
## [1] "class: Disabled:"
##                                         Age   Married.fctrMarried 
##           -0.79408299            0.01681048           -0.75127170 
## Married.fctrSeparated 
##            0.30130582 
## [1] "class: Employed:"
##                                                 Age 
##                3.32044469               -0.02694435 
##       Married.fctrMarried Married.fctrNever Married 
##                0.18106620               -0.28269559 
##     Married.fctrSeparated       Married.fctrWidowed 
##               -0.10075966               -0.46256333 
## [1] "class: Not.in.Labor.Force:"
##                                                 Age 
##                3.45602240               -0.07655272 
##       Married.fctrMarried Married.fctrNever Married 
##                0.29037877                0.24408828 
##       Married.fctrWidowed 
##                0.38951353 
## [1] "class: Retired:"
##                                                 Age 
##                -6.6894460                 0.1207445 
##       Married.fctrMarried Married.fctrNever Married 
##                 0.3430942                -0.2086412 
##     Married.fctrSeparated       Married.fctrWidowed 
##                -0.3020523                 0.4416997 
## [1] "class: Unemployed:"
##                                                 Age 
##                0.70706190               -0.02811681 
##       Married.fctrMarried Married.fctrNever Married 
##               -0.28571885                0.20779628 
##     Married.fctrSeparated       Married.fctrWidowed 
##                0.17756720               -0.25509042 
## [1] "max lambda < lambdaOpt:"
## [1] "class: Disabled:"
##                                         Age   Married.fctrMarried 
##           -0.79155512            0.01703241           -0.76152146 
## Married.fctrSeparated 
##            0.29311512 
## [1] "class: Employed:"
##                                                 Age 
##                3.34448750               -0.02725668 
##       Married.fctrMarried Married.fctrNever Married 
##                0.18152622               -0.28275686 
##     Married.fctrSeparated       Married.fctrWidowed 
##               -0.10828143               -0.45559728 
## [1] "class: Not.in.Labor.Force:"
##                                                 Age 
##                3.49941749               -0.07762232 
##       Married.fctrMarried Married.fctrNever Married 
##                0.30261115                0.24431988 
##       Married.fctrWidowed 
##                0.42244384 
## [1] "class: Retired:"
##                                                 Age 
##                -6.8056729                 0.1226320 
##       Married.fctrMarried Married.fctrNever Married 
##                 0.3459936                -0.2062815 
##     Married.fctrSeparated       Married.fctrWidowed 
##                -0.3104299                 0.4389381 
## [1] "class: Unemployed:"
##                                                 Age 
##                0.75332300               -0.02884429 
##       Married.fctrMarried Married.fctrNever Married 
##               -0.29106089                0.20042477 
##     Married.fctrSeparated       Married.fctrWidowed 
##                0.17345975               -0.25949726 
## [1] "myfit_mdl: train diagnostics complete: 13.333000 secs"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     3663                  0     513
##   Employed                  0    43079                  3    2053
##   Not.in.Labor.Force        0    10891                  4     252
##   Retired                   0     3911                  0    9702
##   Unemployed                0     2970                  0     102
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.6842487      0.3446629      0.6809553      0.6875283      0.5850822 
## AccuracyPValue  McnemarPValue 
##      0.0000000            NaN 
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     1362                  0     174
##   Employed                  0    15859                  1     738
##   Not.in.Labor.Force        0     4003                  1      95
##   Retired                   0     1404                  1    3601
##   Unemployed                0     1105                  0      26
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##   6.859711e-01   3.481272e-01   6.805339e-01   6.913702e-01   5.850546e-01 
## AccuracyPValue  McnemarPValue 
##  2.504519e-269            NaN 
## [1] "myfit_mdl: predict complete: 14.592000 secs"
##                           id            feats max.nTuningRuns
## 1 Max.cor.Y.rcv.1X1###glmnet Age,Married.fctr               0
##   min.elapsedtime.everything min.elapsedtime.final max.Accuracy.fit
## 1                     12.169                10.348        0.6842487
##   max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1             0.6809553             0.6875283     0.3446629
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.6859711             0.6805339             0.6913702
##   max.Kappa.OOB
## 1     0.3481272
## [1] "myfit_mdl: exit: 14.598000 secs"
if (glbMdlCheckRcv) {
    # rcv_n_folds == 1 & rcv_n_repeats > 1 crashes
    for (rcv_n_folds in seq(3, glb_rcv_n_folds + 2, 2))
        for (rcv_n_repeats in seq(1, glb_rcv_n_repeats + 2, 2)) {
            
            # Experiment specific code to avoid caret crash
    #         lcl_tune_models_df <- rbind(data.frame()
    #                             ,data.frame(method = "glmnet", parameter = "alpha", 
    #                                         vals = "0.100 0.325 0.550 0.775 1.000")
    #                             ,data.frame(method = "glmnet", parameter = "lambda",
    #                                         vals = "9.342e-02")    
    #                                     )
            
            ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst =
                list(
                id.prefix = paste0("Max.cor.Y.rcv.", rcv_n_folds, "X", rcv_n_repeats), 
                type = glb_model_type, 
    # tune.df = lcl_tune_models_df,            
                trainControl.method = "repeatedcv",
                trainControl.number = rcv_n_folds, 
                trainControl.repeats = rcv_n_repeats,
                trainControl.classProbs = glb_is_classification,
                trainControl.summaryFunction = glbMdlMetricSummaryFn,
                train.method = "glmnet", train.metric = glbMdlMetricSummary, 
                train.maximize = glbMdlMetricMaximize)),
                                indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    # Add parallel coordinates graph of glb_models_df[, glbMdlMetricsEval] to evaluate cv parameters
    tmp_models_cols <- c("id", "max.nTuningRuns",
                        glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                        grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
    print(myplot_parcoord(obs_df = subset(glb_models_df, 
                                          grepl("Max.cor.Y.rcv.", id, fixed = TRUE), 
                                            select = -feats)[, tmp_models_cols],
                          id_var = "id"))
}
        
# Useful for stacking decisions
# fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
#                     paste0("fit.models_0_", "Max.cor.Y[rcv.1X1.cp.0|]"), major.inc = FALSE,
#                                     label.minor = "rpart")
# 
# ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
#     id.prefix = "Max.cor.Y.rcv.1X1.cp.0", type = glb_model_type, trainControl.method = "none",
#     train.method = "rpart",
#     tune.df=data.frame(method="rpart", parameter="cp", min=0.0, max=0.0, by=0.1))),
#                     indepVar=max_cor_y_x_vars, rsp_var=glb_rsp_var, 
#                     fit_df=glbObsFit, OOB_df=glbObsOOB)

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
# if (glb_is_regression || glb_is_binomial) # For multinomials this model will be run next by default
ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = "Max.cor.Y", 
                        type = glb_model_type, trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds, 
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        trainControl.allowParallel = glbMdlAllowParallel,                        
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = "rpart")),
                    indepVar = max_cor_y_x_vars, rsp_var = glb_rsp_var, 
                    fit_df = glbObsFit, OOB_df = glbObsOOB)
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Max.cor.Y##rcv#rpart"
## [1] "    indepVar: Age,Married.fctr"
## [1] "myfit_mdl: setup complete: 0.691000 secs"
## Loading required package: rpart
## + Fold1.Rep1: cp=0.0001406 
## - Fold1.Rep1: cp=0.0001406 
## + Fold2.Rep1: cp=0.0001406 
## - Fold2.Rep1: cp=0.0001406 
## + Fold3.Rep1: cp=0.0001406 
## - Fold3.Rep1: cp=0.0001406 
## + Fold1.Rep2: cp=0.0001406 
## - Fold1.Rep2: cp=0.0001406 
## + Fold2.Rep2: cp=0.0001406 
## - Fold2.Rep2: cp=0.0001406 
## + Fold3.Rep2: cp=0.0001406 
## - Fold3.Rep2: cp=0.0001406 
## + Fold1.Rep3: cp=0.0001406 
## - Fold1.Rep3: cp=0.0001406 
## + Fold2.Rep3: cp=0.0001406 
## - Fold2.Rep3: cp=0.0001406 
## + Fold3.Rep3: cp=0.0001406 
## - Fold3.Rep3: cp=0.0001406 
## Aggregating results
## Selecting tuning parameters
## Fitting cp = 0.000141 on full training set
## [1] "myfit_mdl: train complete: 15.491000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = "Max.cor.Y", : model's bestTune found at an extreme of
## tuneGrid for parameter: cp
## Loading required package: rpart.plot

## Call:
## rpart(formula = .outcome ~ ., control = list(minsplit = 20, minbucket = 7, 
##     cp = 0, maxcompete = 4, maxsurrogate = 5, usesurrogate = 2, 
##     surrogatestyle = 0, maxdepth = 30, xval = 0))
##   n= 77143 
## 
##             CP nsplit rel error
## 1 0.2493439140      0 1.0000000
## 2 0.0896338415      1 0.7506561
## 3 0.0007185704      2 0.6610222
## 4 0.0002999250      4 0.6595851
## 5 0.0001405899     10 0.6577106
## 
## Variable importance
##                 Age Married.fctrWidowed 
##                  89                  11 
## 
## Node number 1: 77143 observations,    complexity param=0.2493439
##   predicted class=Employed            expected loss=0.4149178  P(node) =1
##     class counts:  4176 45135 11147 13613  3072
##    probabilities: 0.054 0.585 0.144 0.176 0.040 
##   left son=2 (61353 obs) right son=3 (15790 obs)
##   Primary splits:
##       Age                       < 63.5 to the left,  improve=8858.26400, (0 missing)
##       Married.fctrWidowed       < 0.5  to the left,  improve=2212.80200, (0 missing)
##       Married.fctrNever Married < 0.5  to the right, improve=1406.87800, (0 missing)
##       Married.fctrMarried       < 0.5  to the right, improve= 568.87570, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=  27.73184, (0 missing)
##   Surrogate splits:
##       Married.fctrWidowed < 0.5  to the left,  agree=0.831, adj=0.173, (0 split)
## 
## Node number 2: 61353 observations,    complexity param=0.08963384
##   predicted class=Employed            expected loss=0.3178003  P(node) =0.7953152
##     class counts:  3455 41855 10786  2352  2905
##    probabilities: 0.056 0.682 0.176 0.038 0.047 
##   left son=4 (55227 obs) right son=5 (6126 obs)
##   Primary splits:
##       Age                       < 19.5 to the right, improve=3276.07000, (0 missing)
##       Married.fctrNever Married < 0.5  to the left,  improve=1005.29500, (0 missing)
##       Married.fctrMarried       < 0.5  to the right, improve= 661.88050, (0 missing)
##       Married.fctrWidowed       < 0.5  to the left,  improve=  75.61422, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=  11.33257, (0 missing)
## 
## Node number 3: 15790 observations,    complexity param=0.000299925
##   predicted class=Retired             expected loss=0.2868271  P(node) =0.2046848
##     class counts:   721  3280   361 11261   167
##    probabilities: 0.046 0.208 0.023 0.713 0.011 
##   left son=6 (6763 obs) right son=7 (9027 obs)
##   Primary splits:
##       Age                       < 70.5 to the left,  improve=476.176400, (0 missing)
##       Married.fctrWidowed       < 0.5  to the left,  improve=121.490300, (0 missing)
##       Married.fctrMarried       < 0.5  to the right, improve= 28.613000, (0 missing)
##       Married.fctrNever Married < 0.5  to the right, improve= 12.000990, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=  7.042472, (0 missing)
##   Surrogate splits:
##       Married.fctrNever Married < 0.5  to the right, agree=0.576, adj=0.010, (0 split)
##       Married.fctrWidowed       < 0.5  to the left,  agree=0.575, adj=0.008, (0 split)
##       Married.fctrSeparated     < 0.5  to the right, agree=0.572, adj=0.000, (0 split)
## 
## Node number 4: 55227 observations
##   predicted class=Employed            expected loss=0.2679124  P(node) =0.7159042
##     class counts:  3386 40431  6493  2348  2569
##    probabilities: 0.061 0.732 0.118 0.043 0.047 
## 
## Node number 5: 6126 observations,    complexity param=0.0007185704
##   predicted class=Not.in.Labor.Force  expected loss=0.2992165  P(node) =0.07941096
##     class counts:    69  1424  4293     4   336
##    probabilities: 0.011 0.232 0.701 0.001 0.055 
##   left son=10 (2249 obs) right son=11 (3877 obs)
##   Primary splits:
##       Age                       < 17.5 to the right, improve=240.7698000, (0 missing)
##       Married.fctrNever Married < 0.5  to the left,  improve=  4.2843080, (0 missing)
##       Married.fctrMarried       < 0.5  to the right, improve=  3.8272960, (0 missing)
##       Married.fctrSeparated     < 0.5  to the left,  improve=  0.3026384, (0 missing)
##   Surrogate splits:
##       Married.fctrMarried < 0.5  to the right, agree=0.635, adj=0.007, (0 split)
## 
## Node number 6: 6763 observations,    complexity param=0.000299925
##   predicted class=Retired             expected loss=0.4422594  P(node) =0.08766836
##     class counts:   421  2253   200  3772   117
##    probabilities: 0.062 0.333 0.030 0.558 0.017 
##   left son=12 (2239 obs) right son=13 (4524 obs)
##   Primary splits:
##       Age                       < 65.5 to the left,  improve=57.801150, (0 missing)
##       Married.fctrMarried       < 0.5  to the left,  improve=15.646450, (0 missing)
##       Married.fctrWidowed       < 0.5  to the left,  improve= 8.354322, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve= 4.612768, (0 missing)
##       Married.fctrNever Married < 0.5  to the right, improve= 3.596623, (0 missing)
## 
## Node number 7: 9027 observations
##   predicted class=Retired             expected loss=0.1703778  P(node) =0.1170164
##     class counts:   300  1027   161  7489    50
##    probabilities: 0.033 0.114 0.018 0.830 0.006 
## 
## Node number 10: 2249 observations,    complexity param=0.0007185704
##   predicted class=Not.in.Labor.Force  expected loss=0.4988884  P(node) =0.02915365
##     class counts:    28   890  1127     2   202
##    probabilities: 0.012 0.396 0.501 0.001 0.090 
##   left son=20 (1106 obs) right son=21 (1143 obs)
##   Primary splits:
##       Age                       < 18.5 to the right, improve=23.60859000, (0 missing)
##       Married.fctrNever Married < 0.5  to the left,  improve= 2.01601700, (0 missing)
##       Married.fctrMarried       < 0.5  to the right, improve= 0.75289140, (0 missing)
##       Married.fctrSeparated     < 0.5  to the left,  improve= 0.09759261, (0 missing)
##   Surrogate splits:
##       Married.fctrNever Married < 0.5  to the left,  agree=0.517, adj=0.017, (0 split)
##       Married.fctrMarried       < 0.5  to the right, agree=0.515, adj=0.014, (0 split)
##       Married.fctrSeparated     < 0.5  to the right, agree=0.509, adj=0.002, (0 split)
## 
## Node number 11: 3877 observations
##   predicted class=Not.in.Labor.Force  expected loss=0.1833892  P(node) =0.05025731
##     class counts:    41   534  3166     2   134
##    probabilities: 0.011 0.138 0.817 0.001 0.035 
## 
## Node number 12: 2239 observations,    complexity param=0.000299925
##   predicted class=Retired             expected loss=0.5475659  P(node) =0.02902402
##     class counts:   190   914    77  1013    45
##    probabilities: 0.085 0.408 0.034 0.452 0.020 
##   left son=24 (730 obs) right son=25 (1509 obs)
##   Primary splits:
##       Married.fctrMarried       < 0.5  to the left,  improve=9.408466, (0 missing)
##       Age                       < 64.5 to the left,  improve=8.638895, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=3.217616, (0 missing)
##       Married.fctrNever Married < 0.5  to the right, improve=1.756960, (0 missing)
##       Married.fctrWidowed       < 0.5  to the left,  improve=1.238922, (0 missing)
##   Surrogate splits:
##       Married.fctrWidowed       < 0.5  to the right, agree=0.753, adj=0.242, (0 split)
##       Married.fctrNever Married < 0.5  to the right, agree=0.741, adj=0.205, (0 split)
##       Married.fctrSeparated     < 0.5  to the right, agree=0.686, adj=0.037, (0 split)
## 
## Node number 13: 4524 observations
##   predicted class=Retired             expected loss=0.3901415  P(node) =0.05864434
##     class counts:   231  1339   123  2759    72
##    probabilities: 0.051 0.296 0.027 0.610 0.016 
## 
## Node number 20: 1106 observations
##   predicted class=Employed            expected loss=0.534358  P(node) =0.01433701
##     class counts:    16   515   469     2   104
##    probabilities: 0.014 0.466 0.424 0.002 0.094 
## 
## Node number 21: 1143 observations
##   predicted class=Not.in.Labor.Force  expected loss=0.424322  P(node) =0.01481664
##     class counts:    12   375   658     0    98
##    probabilities: 0.010 0.328 0.576 0.000 0.086 
## 
## Node number 24: 730 observations,    complexity param=0.000299925
##   predicted class=Employed            expected loss=0.6068493  P(node) =0.009462945
##     class counts:   110   287    27   284    22
##    probabilities: 0.151 0.393 0.037 0.389 0.030 
##   left son=48 (553 obs) right son=49 (177 obs)
##   Primary splits:
##       Married.fctrWidowed       < 0.5  to the left,  improve=3.8573460, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=1.8347000, (0 missing)
##       Age                       < 64.5 to the left,  improve=1.8184380, (0 missing)
##       Married.fctrNever Married < 0.5  to the left,  improve=0.7679924, (0 missing)
## 
## Node number 25: 1509 observations,    complexity param=0.000299925
##   predicted class=Retired             expected loss=0.5168986  P(node) =0.01956107
##     class counts:    80   627    50   729    23
##    probabilities: 0.053 0.416 0.033 0.483 0.015 
##   left son=50 (755 obs) right son=51 (754 obs)
##   Primary splits:
##       Age < 64.5 to the left,  improve=7.060871, (0 missing)
## 
## Node number 48: 553 observations,    complexity param=0.000299925
##   predicted class=Employed            expected loss=0.5949367  P(node) =0.007168505
##     class counts:    90   224    24   195    20
##    probabilities: 0.163 0.405 0.043 0.353 0.036 
##   left son=96 (403 obs) right son=97 (150 obs)
##   Primary splits:
##       Married.fctrNever Married < 0.5  to the left,  improve=1.8459710, (0 missing)
##       Married.fctrSeparated     < 0.5  to the right, improve=1.3472590, (0 missing)
##       Age                       < 64.5 to the left,  improve=0.5622227, (0 missing)
## 
## Node number 49: 177 observations
##   predicted class=Retired             expected loss=0.4971751  P(node) =0.00229444
##     class counts:    20    63     3    89     2
##    probabilities: 0.113 0.356 0.017 0.503 0.011 
## 
## Node number 50: 755 observations
##   predicted class=Employed            expected loss=0.5470199  P(node) =0.009787019
##     class counts:    39   342    35   323    16
##    probabilities: 0.052 0.453 0.046 0.428 0.021 
## 
## Node number 51: 754 observations
##   predicted class=Retired             expected loss=0.4615385  P(node) =0.009774056
##     class counts:    41   285    15   406     7
##    probabilities: 0.054 0.378 0.020 0.538 0.009 
## 
## Node number 96: 403 observations
##   predicted class=Employed            expected loss=0.5707196  P(node) =0.005224064
##     class counts:    67   173    16   132    15
##    probabilities: 0.166 0.429 0.040 0.328 0.037 
## 
## Node number 97: 150 observations
##   predicted class=Retired             expected loss=0.58  P(node) =0.001944441
##     class counts:    23    51     8    63     5
##    probabilities: 0.153 0.340 0.053 0.420 0.033 
## 
## n= 77143 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 77143 32008 Employed (0.054 0.59 0.14 0.18 0.04)  
##    2) Age< 63.5 61353 19498 Employed (0.056 0.68 0.18 0.038 0.047)  
##      4) Age>=19.5 55227 14796 Employed (0.061 0.73 0.12 0.043 0.047) *
##      5) Age< 19.5 6126  1833 Not.in.Labor.Force (0.011 0.23 0.7 0.00065 0.055)  
##       10) Age>=17.5 2249  1122 Not.in.Labor.Force (0.012 0.4 0.5 0.00089 0.09)  
##         20) Age>=18.5 1106   591 Employed (0.014 0.47 0.42 0.0018 0.094) *
##         21) Age< 18.5 1143   485 Not.in.Labor.Force (0.01 0.33 0.58 0 0.086) *
##       11) Age< 17.5 3877   711 Not.in.Labor.Force (0.011 0.14 0.82 0.00052 0.035) *
##    3) Age>=63.5 15790  4529 Retired (0.046 0.21 0.023 0.71 0.011)  
##      6) Age< 70.5 6763  2991 Retired (0.062 0.33 0.03 0.56 0.017)  
##       12) Age< 65.5 2239  1226 Retired (0.085 0.41 0.034 0.45 0.02)  
##         24) Married.fctrMarried< 0.5 730   443 Employed (0.15 0.39 0.037 0.39 0.03)  
##           48) Married.fctrWidowed< 0.5 553   329 Employed (0.16 0.41 0.043 0.35 0.036)  
##             96) Married.fctrNever Married< 0.5 403   230 Employed (0.17 0.43 0.04 0.33 0.037) *
##             97) Married.fctrNever Married>=0.5 150    87 Retired (0.15 0.34 0.053 0.42 0.033) *
##           49) Married.fctrWidowed>=0.5 177    88 Retired (0.11 0.36 0.017 0.5 0.011) *
##         25) Married.fctrMarried>=0.5 1509   780 Retired (0.053 0.42 0.033 0.48 0.015)  
##           50) Age< 64.5 755   413 Employed (0.052 0.45 0.046 0.43 0.021) *
##           51) Age>=64.5 754   348 Retired (0.054 0.38 0.02 0.54 0.0093) *
##       13) Age>=65.5 4524  1765 Retired (0.051 0.3 0.027 0.61 0.016) *
##      7) Age>=70.5 9027  1538 Retired (0.033 0.11 0.018 0.83 0.0055) *
## [1] "myfit_mdl: train diagnostics complete: 16.344000 secs"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     3508                 53     615
##   Employed                  0    41461                909    2765
##   Not.in.Labor.Force        0     7013               3824     310
##   Retired                   0     2805                  2   10806
##   Unemployed                0     2704                232     136
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.7271042      0.4763005      0.7239458      0.7302455      0.5850822 
## AccuracyPValue  McnemarPValue 
##      0.0000000            NaN 
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                  0     1280                 28     228
##   Employed                  0    15235                358    1005
##   Not.in.Labor.Force        0     2578               1399     122
##   Retired                   0      995                  1    4010
##   Unemployed                0      993                 98      40
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.7276701      0.4783439      0.7224493      0.7328442      0.5850546 
## AccuracyPValue  McnemarPValue 
##      0.0000000            NaN 
## [1] "myfit_mdl: predict complete: 16.773000 secs"
##                     id            feats max.nTuningRuns
## 1 Max.cor.Y##rcv#rpart Age,Married.fctr               5
##   min.elapsedtime.everything min.elapsedtime.final max.Accuracy.fit
## 1                     14.705                 0.399        0.7264431
##   max.AccuracyLower.fit max.AccuracyUpper.fit max.Kappa.fit
## 1             0.7239458             0.7302455     0.4771251
##   max.Accuracy.OOB max.AccuracyLower.OOB max.AccuracyUpper.OOB
## 1        0.7276701             0.7224493             0.7328442
##   max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1     0.4783439        0.002327336     0.005671842
## [1] "myfit_mdl: exit: 16.783000 secs"
if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Poly"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.day\\.minutes\\.poly\\.", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = "Max.cor.Y.Time.Poly", 
            type = glb_model_type, trainControl.method = "repeatedcv",
            trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,            
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if ((length(glbFeatsDateTime) > 0) && 
    (sum(grepl(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
               names(glbObsAll))) > 0)) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Max.cor.Y.Time.Lag"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars, 
            grep(paste(names(glbFeatsDateTime), "\\.last[[:digit:]]", sep = ""),
                        names(glbObsAll), value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Time.Lag", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,        
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

if (length(glbFeatsText) > 0) {
    fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
                    paste0("fit.models_0_", "Txt.*"), major.inc = FALSE,
                                    label.minor = "glmnet")

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.(?!([T|P]\\.))", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.nonTP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,                                
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.T\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyT", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)

    indepVars <- c(max_cor_y_x_vars)
    for (txtFeat in names(glbFeatsText))
        indepVars <- union(indepVars, 
            grep(paste(str_to_upper(substr(txtFeat, 1, 1)), "\\.P\\.", sep = ""),
                        names(glbObsAll), perl = TRUE, value = TRUE))
    indepVars <- myadjustInteractionFeats(glb_feats_df, indepVars)
    ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
        id.prefix = "Max.cor.Y.Text.onlyP", 
        type = glb_model_type, 
        tune.df = glbMdlTuneParams,        
        trainControl.method = "repeatedcv",
        trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
        trainControl.classProbs = glb_is_classification,
        trainControl.summaryFunction = glbMdlMetricSummaryFn,
        trainControl.allowParallel = glbMdlAllowParallel,        
        train.metric = glbMdlMetricSummary, 
        train.maximize = glbMdlMetricMaximize,    
        train.method = "glmnet")),
        indepVar = indepVars,
        rsp_var = glb_rsp_var, 
        fit_df = glbObsFit, OOB_df = glbObsOOB)
}

# Interactions.High.cor.Y
# Takes a lon time for this case
# if (length(int_feats <- setdiff(setdiff(unique(glb_feats_df$cor.high.X), NA), 
#                                 subset(glb_feats_df, nzv)$id)) > 0) {
#     fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
#                     paste0("fit.models_0_", "Interact.High.cor.Y"), major.inc = FALSE,
#                                     label.minor = "glmnet")
# 
#     ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
#         id.prefix="Interact.High.cor.Y", 
#         type=glb_model_type, trainControl.method="repeatedcv",
#         trainControl.number=glb_rcv_n_folds, trainControl.repeats=glb_rcv_n_repeats,
#         trainControl.classProbs = glb_is_classification,
#         trainControl.summaryFunction = glbMdlMetricSummaryFn,
#         trainControl.allowParallel = glbMdlAllowParallel,
#         train.metric = glbMdlMetricSummary, 
#         train.maximize = glbMdlMetricMaximize,    
#         train.method="glmnet")),
#         indepVar=c(max_cor_y_x_vars, paste(max_cor_y_x_vars[1], int_feats, sep=":")),
#         rsp_var=glb_rsp_var, 
#         fit_df=glbObsFit, OOB_df=glbObsOOB)
# }    

# Low.cor.X
# Takes a long time for this case
# fit.models_0_chunk_df <- myadd_chunk(fit.models_0_chunk_df, 
#                         paste0("fit.models_0_", "Low.cor.X"), major.inc = FALSE,
#                                      label.minor = "glmnet")
# indepVar <- mygetIndepVar(glb_feats_df)
# ret_lst <- myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
#             id.prefix = "Low.cor.X", 
#             type = glb_model_type, 
#             tune.df = glbMdlTuneParams,        
#             trainControl.method = "repeatedcv",
#             trainControl.number = glb_rcv_n_folds, trainControl.repeats = glb_rcv_n_repeats,
#             trainControl.classProbs = glb_is_classification,
#             trainControl.summaryFunction = glbMdlMetricSummaryFn,
#             trainControl.allowParallel = glbMdlAllowParallel,
#             train.metric = glbMdlMetricSummary, 
#             train.maximize = glbMdlMetricMaximize,    
#             train.method = "glmnet")),
#         indepVar = indepVar, rsp_var = glb_rsp_var, 
#         fit_df = glbObsFit, OOB_df = glbObsOOB)
# 
# fit.models_0_chunk_df <- 
#     myadd_chunk(fit.models_0_chunk_df, "fit.models_0_end", major.inc = FALSE,
#                 label.minor = "teardown")

rm(ret_lst)

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor     bgn    end elapsed
## 16 fit.models          8          0           0 118.503 153.03  34.527
## 17 fit.models          8          1           1 153.030     NA      NA
fit.models_1_chunk_df <- myadd_chunk(NULL, "fit.models_1_bgn", label.minor = "setup")
##              label step_major step_minor label_minor     bgn end elapsed
## 1 fit.models_1_bgn          1          0       setup 153.862  NA      NA
# refactor code for outliers / ensure all model runs exclude outliers in this chunk ???

#stop(here"); glb2Sav(); all.equal(glb_models_df, sav_models_df)
topindep_var <- NULL; interact_vars <- NULL;
for (mdl_id_pfx in names(glbMdlFamilies)) {
    fit.models_1_chunk_df <- 
        myadd_chunk(fit.models_1_chunk_df, paste0("fit.models_1_", mdl_id_pfx),
                    major.inc = FALSE, label.minor = "setup")

    indepVar <- NULL;

    if (grepl("\\.Interact", mdl_id_pfx)) {
        if (is.null(topindep_var) && is.null(interact_vars)) {
        #   select best glmnet model upto now
            dsp_models_df <- orderBy(model_sel_frmla <- get_model_sel_frmla(),
                                     glb_models_df)
            dsp_models_df <- subset(dsp_models_df, 
                                    grepl(".glmnet", id, fixed = TRUE))
            bst_mdl_id <- dsp_models_df$id[1]
            mdl_id_pfx <- 
                paste(c(head(unlist(strsplit(bst_mdl_id, "[.]")), -1), "Interact"),
                      collapse=".")
        #   select important features
            if (is.null(bst_featsimp_df <- 
                        myget_feats_importance(glb_models_lst[[bst_mdl_id]]))) {
                warning("Base model for RFE.Interact: ", bst_mdl_id, 
                        " has no important features")
                next
            }    
            
            topindep_ix <- 1
            while (is.null(topindep_var) && (topindep_ix <= nrow(bst_featsimp_df))) {
                topindep_var <- row.names(bst_featsimp_df)[topindep_ix]
                if (grepl(".fctr", topindep_var, fixed=TRUE))
                    topindep_var <- 
                        paste0(unlist(strsplit(topindep_var, ".fctr"))[1], ".fctr")
                if (topindep_var %in% names(glbFeatsInteractionOnly)) {
                    topindep_var <- NULL; topindep_ix <- topindep_ix + 1
                } else break
            }
            
        #   select features with importance > max(10, importance of .rnorm) & is not highest
        #       combine factor dummy features to just the factor feature
            if (length(pos_rnorm <- 
                       grep(".rnorm", row.names(bst_featsimp_df), fixed=TRUE)) > 0)
                imp_rnorm <- bst_featsimp_df[pos_rnorm, 1] else
                imp_rnorm <- NA    
            imp_cutoff <- max(10, imp_rnorm, na.rm=TRUE)
            interact_vars <- 
                tail(row.names(subset(bst_featsimp_df, 
                                      imp > imp_cutoff)), -1)
            if (length(interact_vars) > 0) {
                interact_vars <-
                    myadjustInteractionFeats(glb_feats_df, myextract_actual_feats(interact_vars))
                interact_vars <- 
                    interact_vars[!grepl(topindep_var, interact_vars, fixed=TRUE)]
            }
            ### bid0_sp only
#             interact_vars <- c(
#     "biddable", "D.ratio.sum.TfIdf.wrds.n", "D.TfIdf.sum.stem.stop.Ratio", "D.sum.TfIdf",
#     "D.TfIdf.sum.post.stop", "D.TfIdf.sum.post.stem", "D.ratio.wrds.stop.n.wrds.n", "D.chrs.uppr.n.log",
#     "D.chrs.n.log", "color.fctr"
#     # , "condition.fctr", "prdl.my.descr.fctr"
#                                 )
#            interact_vars <- setdiff(interact_vars, c("startprice.dgt2.is9", "color.fctr"))
            ###
            indepVar <- myextract_actual_feats(row.names(bst_featsimp_df))
            indepVar <- setdiff(indepVar, topindep_var)
            if (length(interact_vars) > 0) {
                indepVar <- 
                    setdiff(indepVar, myextract_actual_feats(interact_vars))
                indepVar <- c(indepVar, 
                    paste(topindep_var, setdiff(interact_vars, topindep_var), 
                          sep = "*"))
            } else indepVar <- union(indepVar, topindep_var)
        }
    }
    
    if (is.null(indepVar))
        indepVar <- glb_mdl_feats_lst[[mdl_id_pfx]]

    if (is.null(indepVar) && grepl("RFE\\.", mdl_id_pfx))
        indepVar <- myextract_actual_feats(predictors(rfe_fit_results))
    
    if (is.null(indepVar))
        indepVar <- mygetIndepVar(glb_feats_df)
    
    if ((length(indepVar) == 1) && (grepl("^%<d-%", indepVar))) {    
        indepVar <- 
            eval(parse(text = str_trim(unlist(strsplit(indepVar, "%<d-%"))[2])))
    }    

    indepVar <- myadjustInteractionFeats(glb_feats_df, indepVar)
    
    if (grepl("\\.Interact", mdl_id_pfx)) { 
        # if (method != tail(unlist(strsplit(bst_mdl_id, "[.]")), 1)) next
        if (is.null(glbMdlFamilies[[mdl_id_pfx]])) {
            if (!is.null(glbMdlFamilies[["Best.Interact"]]))
                glbMdlFamilies[[mdl_id_pfx]] <-
                    glbMdlFamilies[["Best.Interact"]]
        }
    }
    
    if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
        fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                         glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    } else fitobs_df <- glbObsFit

    if (is.null(glbMdlFamilies[[mdl_id_pfx]]))
        mdl_methods <- glbMdlMethods else
        mdl_methods <- glbMdlFamilies[[mdl_id_pfx]]    

    for (method in mdl_methods) {
        if (method %in% c("rpart", "rf")) {
            # rpart:    fubar's the tree
            # rf:       skip the scenario w/ .rnorm for speed
            indepVar <- setdiff(indepVar, c(".rnorm"))
            #mdl_id <- paste0(mdl_id_pfx, ".no.rnorm")
        } 

        fit.models_1_chunk_df <- myadd_chunk(fit.models_1_chunk_df, 
                            paste0("fit.models_1_", mdl_id_pfx), major.inc = FALSE,
                                    label.minor = method)

        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
            id.prefix = mdl_id_pfx, 
            type = glb_model_type, 
            tune.df = glbMdlTuneParams,
            trainControl.method = "repeatedcv", # or "none" if nominalWorkflow is crashing
            trainControl.number = glb_rcv_n_folds,
            trainControl.repeats = glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            trainControl.allowParallel = glbMdlAllowParallel,            
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method = method)),
            indepVar = indepVar, rsp_var = glb_rsp_var, 
            fit_df = fitobs_df, OOB_df = glbObsOOB)
        
#         ntv_mdl <- glmnet(x = as.matrix(
#                               fitobs_df[, indepVar]), 
#                           y = as.factor(as.character(
#                               fitobs_df[, glb_rsp_var])),
#                           family = "multinomial")
#         bgn = 1; end = 100;
#         ntv_mdl <- glmnet(x = as.matrix(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, indepVar]), 
#                           y = as.factor(as.character(
#                               subset(fitobs_df, pop.fctr != "crypto")[bgn:end, glb_rsp_var])),
#                           family = "multinomial")
    }
}
##                label step_major step_minor label_minor     bgn     end
## 1   fit.models_1_bgn          1          0       setup 153.862 153.873
## 2 fit.models_1_All.X          1          1       setup 153.873      NA
##   elapsed
## 1   0.011
## 2      NA
##                label step_major step_minor label_minor     bgn    end
## 2 fit.models_1_All.X          1          1       setup 153.873 153.88
## 3 fit.models_1_All.X          1          2      glmnet 153.880     NA
##   elapsed
## 2   0.007
## 3      NA
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: All.X##rcv#glmnet"
## [1] "    indepVar: Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold"
## [1] "myfit_mdl: setup complete: 0.732000 secs"
## + Fold1.Rep1: alpha=0.100, lambda=0.1012 
## - Fold1.Rep1: alpha=0.100, lambda=0.1012 
## + Fold1.Rep1: alpha=0.325, lambda=0.1012 
## - Fold1.Rep1: alpha=0.325, lambda=0.1012 
## + Fold1.Rep1: alpha=0.550, lambda=0.1012 
## - Fold1.Rep1: alpha=0.550, lambda=0.1012 
## + Fold1.Rep1: alpha=0.775, lambda=0.1012 
## - Fold1.Rep1: alpha=0.775, lambda=0.1012 
## + Fold1.Rep1: alpha=1.000, lambda=0.1012 
## - Fold1.Rep1: alpha=1.000, lambda=0.1012 
## + Fold2.Rep1: alpha=0.100, lambda=0.1012 
## - Fold2.Rep1: alpha=0.100, lambda=0.1012 
## + Fold2.Rep1: alpha=0.325, lambda=0.1012 
## - Fold2.Rep1: alpha=0.325, lambda=0.1012 
## + Fold2.Rep1: alpha=0.550, lambda=0.1012 
## - Fold2.Rep1: alpha=0.550, lambda=0.1012 
## + Fold2.Rep1: alpha=0.775, lambda=0.1012 
## - Fold2.Rep1: alpha=0.775, lambda=0.1012 
## + Fold2.Rep1: alpha=1.000, lambda=0.1012 
## - Fold2.Rep1: alpha=1.000, lambda=0.1012 
## + Fold3.Rep1: alpha=0.100, lambda=0.1012 
## - Fold3.Rep1: alpha=0.100, lambda=0.1012 
## + Fold3.Rep1: alpha=0.325, lambda=0.1012 
## - Fold3.Rep1: alpha=0.325, lambda=0.1012 
## + Fold3.Rep1: alpha=0.550, lambda=0.1012 
## - Fold3.Rep1: alpha=0.550, lambda=0.1012 
## + Fold3.Rep1: alpha=0.775, lambda=0.1012 
## - Fold3.Rep1: alpha=0.775, lambda=0.1012 
## + Fold3.Rep1: alpha=1.000, lambda=0.1012 
## - Fold3.Rep1: alpha=1.000, lambda=0.1012 
## + Fold1.Rep2: alpha=0.100, lambda=0.1012 
## - Fold1.Rep2: alpha=0.100, lambda=0.1012 
## + Fold1.Rep2: alpha=0.325, lambda=0.1012 
## - Fold1.Rep2: alpha=0.325, lambda=0.1012 
## + Fold1.Rep2: alpha=0.550, lambda=0.1012 
## - Fold1.Rep2: alpha=0.550, lambda=0.1012 
## + Fold1.Rep2: alpha=0.775, lambda=0.1012 
## - Fold1.Rep2: alpha=0.775, lambda=0.1012 
## + Fold1.Rep2: alpha=1.000, lambda=0.1012 
## - Fold1.Rep2: alpha=1.000, lambda=0.1012 
## + Fold2.Rep2: alpha=0.100, lambda=0.1012 
## - Fold2.Rep2: alpha=0.100, lambda=0.1012 
## + Fold2.Rep2: alpha=0.325, lambda=0.1012 
## - Fold2.Rep2: alpha=0.325, lambda=0.1012 
## + Fold2.Rep2: alpha=0.550, lambda=0.1012 
## - Fold2.Rep2: alpha=0.550, lambda=0.1012 
## + Fold2.Rep2: alpha=0.775, lambda=0.1012 
## - Fold2.Rep2: alpha=0.775, lambda=0.1012 
## + Fold2.Rep2: alpha=1.000, lambda=0.1012 
## - Fold2.Rep2: alpha=1.000, lambda=0.1012 
## + Fold3.Rep2: alpha=0.100, lambda=0.1012 
## - Fold3.Rep2: alpha=0.100, lambda=0.1012 
## + Fold3.Rep2: alpha=0.325, lambda=0.1012 
## - Fold3.Rep2: alpha=0.325, lambda=0.1012 
## + Fold3.Rep2: alpha=0.550, lambda=0.1012 
## - Fold3.Rep2: alpha=0.550, lambda=0.1012 
## + Fold3.Rep2: alpha=0.775, lambda=0.1012 
## - Fold3.Rep2: alpha=0.775, lambda=0.1012 
## + Fold3.Rep2: alpha=1.000, lambda=0.1012 
## - Fold3.Rep2: alpha=1.000, lambda=0.1012 
## + Fold1.Rep3: alpha=0.100, lambda=0.1012 
## - Fold1.Rep3: alpha=0.100, lambda=0.1012 
## + Fold1.Rep3: alpha=0.325, lambda=0.1012 
## - Fold1.Rep3: alpha=0.325, lambda=0.1012 
## + Fold1.Rep3: alpha=0.550, lambda=0.1012 
## - Fold1.Rep3: alpha=0.550, lambda=0.1012 
## + Fold1.Rep3: alpha=0.775, lambda=0.1012 
## - Fold1.Rep3: alpha=0.775, lambda=0.1012 
## + Fold1.Rep3: alpha=1.000, lambda=0.1012 
## - Fold1.Rep3: alpha=1.000, lambda=0.1012 
## + Fold2.Rep3: alpha=0.100, lambda=0.1012 
## - Fold2.Rep3: alpha=0.100, lambda=0.1012 
## + Fold2.Rep3: alpha=0.325, lambda=0.1012 
## - Fold2.Rep3: alpha=0.325, lambda=0.1012 
## + Fold2.Rep3: alpha=0.550, lambda=0.1012 
## - Fold2.Rep3: alpha=0.550, lambda=0.1012 
## + Fold2.Rep3: alpha=0.775, lambda=0.1012 
## - Fold2.Rep3: alpha=0.775, lambda=0.1012 
## + Fold2.Rep3: alpha=1.000, lambda=0.1012 
## - Fold2.Rep3: alpha=1.000, lambda=0.1012 
## + Fold3.Rep3: alpha=0.100, lambda=0.1012 
## - Fold3.Rep3: alpha=0.100, lambda=0.1012 
## + Fold3.Rep3: alpha=0.325, lambda=0.1012 
## - Fold3.Rep3: alpha=0.325, lambda=0.1012 
## + Fold3.Rep3: alpha=0.550, lambda=0.1012 
## - Fold3.Rep3: alpha=0.550, lambda=0.1012 
## + Fold3.Rep3: alpha=0.775, lambda=0.1012 
## - Fold3.Rep3: alpha=0.775, lambda=0.1012 
## + Fold3.Rep3: alpha=1.000, lambda=0.1012 
## - Fold3.Rep3: alpha=1.000, lambda=0.1012 
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 1, lambda = 0.000218 on full training set
## [1] "myfit_mdl: train complete: 1120.893000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: alpha
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: lambda

##             Length Class      Mode     
## a0          380    -none-     numeric  
## beta          5    -none-     list     
## dfmat       380    -none-     numeric  
## df           76    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       76    -none-     numeric  
## dev.ratio    76    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    5    -none-     character
## grouped       1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames       28    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     5    -none-     character
## [1] "min lambda > lambdaOpt:"
## [1] "class: Disabled:"
##                                       
##                          -0.682133676 
##                                .rnorm 
##                           0.016236821 
##                                   Age 
##                           0.052704231 
##  Citizenship.fctrCitizen, Naturalized 
##                          -0.505511515 
##           Citizenship.fctrNon-Citizen 
##                          -0.860459043 
##       Education.fctrBachelor's degree 
##                          -0.629820356 
##        Education.fctrDoctorate degree 
##                          -0.626569025 
##             Education.fctrHigh school 
##                           0.362734617 
##         Education.fctrMaster's degree 
##                          -0.868888624 
##  Education.fctrNo high school diploma 
##                           1.064677342 
##     Education.fctrProfessional degree 
##                          -0.757369329 
## Education.fctrSome college, no degree 
##                           0.115647622 
##                   Married.fctrMarried 
##                          -0.857965891 
##                 Married.fctrSeparated 
##                           0.160275744 
##                     PeopleInHousehold 
##                          -0.016579180 
##              Race.fctrAmerican Indian 
##                           0.009019554 
##                        Race.fctrAsian 
##                          -0.072868661 
##                        Race.fctrBlack 
##                           0.310408699 
##                  Race.fctrMultiracial 
##                           0.092364638 
##             Race.fctrPacific Islander 
##                           0.275381398 
##                    Region.fctrMidwest 
##                          -0.071696043 
##                  Region.fctrNortheast 
##                          -0.016321483 
##                       Region.fctrWest 
##                          -0.105253659 
## [1] "class: Employed:"
##                                       
##                            4.07376570 
##                                .rnorm 
##                            0.01129780 
##  Citizenship.fctrCitizen, Naturalized 
##                            0.08291596 
##           Citizenship.fctrNon-Citizen 
##                            0.07695471 
##       Education.fctrBachelor's degree 
##                            0.15279080 
##        Education.fctrDoctorate degree 
##                            0.76855035 
##             Education.fctrHigh school 
##                           -0.45606953 
##         Education.fctrMaster's degree 
##                            0.25793173 
##  Education.fctrNo high school diploma 
##                           -0.85274987 
##     Education.fctrProfessional degree 
##                            0.53560074 
## Education.fctrSome college, no degree 
##                           -0.21721324 
##                              Hispanic 
##                            0.05415627 
##             Married.fctrNever Married 
##                           -0.20637501 
##                   Married.fctrWidowed 
##                           -0.11773377 
##              Race.fctrAmerican Indian 
##                           -0.36911791 
##                        Race.fctrBlack 
##                           -0.20263429 
##                  Race.fctrMultiracial 
##                           -0.12817419 
##             Race.fctrPacific Islander 
##                           -0.15995753 
##                    Region.fctrMidwest 
##                            0.14673165 
##                  Region.fctrNortheast 
##                            0.08782864 
##                          Sex.fctrMale 
##                            0.22191720 
## [1] "class: Not.in.Labor.Force:"
##                                       
##                            3.24612651 
##                                   Age 
##                           -0.04130075 
##  Citizenship.fctrCitizen, Naturalized 
##                            0.04137445 
##           Citizenship.fctrNon-Citizen 
##                            0.15887442 
##         Education.fctrMaster's degree 
##                           -0.04074203 
##  Education.fctrNo high school diploma 
##                            0.96791390 
## Education.fctrSome college, no degree 
##                            0.23005093 
##                              Hispanic 
##                           -0.10370630 
##                   Married.fctrMarried 
##                            0.25953648 
##             Married.fctrNever Married 
##                            0.33375203 
##                 Married.fctrSeparated 
##                           -0.03752998 
##                   Married.fctrWidowed 
##                            0.58309739 
##                     PeopleInHousehold 
##                            0.14682379 
##                        Race.fctrAsian 
##                            0.43940282 
##                        Race.fctrBlack 
##                           -0.09106900 
##                  Race.fctrMultiracial 
##                            0.05427560 
##                    Region.fctrMidwest 
##                           -0.14995281 
##                          Sex.fctrMale 
##                           -0.71644104 
## [1] "class: Retired:"
##                                                                    .rnorm 
##                         -7.766237327                         -0.016588779 
##                                  Age Citizenship.fctrCitizen, Naturalized 
##                          0.180449160                         -0.210603156 
##          Citizenship.fctrNon-Citizen      Education.fctrBachelor's degree 
##                         -0.291485719                          0.041172954 
##       Education.fctrDoctorate degree            Education.fctrHigh school 
##                          0.034833709                         -0.076053875 
##        Education.fctrMaster's degree                  Married.fctrMarried 
##                          0.235914499                          0.408448441 
##            Married.fctrNever Married                Married.fctrSeparated 
##                         -0.049324597                         -0.215449376 
##                  Married.fctrWidowed                    PeopleInHousehold 
##                          0.527580786                         -0.159180446 
##             Race.fctrAmerican Indian                       Race.fctrAsian 
##                         -0.180429213                          0.149154928 
##                 Race.fctrMultiracial            Race.fctrPacific Islander 
##                         -0.112375180                         -0.184683057 
##                 Region.fctrNortheast                      Region.fctrWest 
##                         -0.001068302                          0.080242502 
##                         Sex.fctrMale 
##                         -0.112094049 
## [1] "class: Unemployed:"
##                                       
##                           1.128478797 
##                                   Age 
##                          -0.003594189 
##             Education.fctrHigh school 
##                           0.006293782 
##  Education.fctrNo high school diploma 
##                          -0.117670195 
## Education.fctrSome college, no degree 
##                          -0.003394560 
##                              Hispanic 
##                           0.171124677 
##                   Married.fctrMarried 
##                          -0.539803262 
##             Married.fctrNever Married 
##                           0.026250406 
##                 Married.fctrSeparated 
##                           0.056433648 
##                   Married.fctrWidowed 
##                          -0.113801986 
##                     PeopleInHousehold 
##                           0.071712840 
##              Race.fctrAmerican Indian 
##                           0.226698090 
##                        Race.fctrAsian 
##                          -0.055242748 
##                        Race.fctrBlack 
##                           0.499911437 
##             Race.fctrPacific Islander 
##                           0.027777413 
##                    Region.fctrMidwest 
##                           0.034678764 
##                  Region.fctrNortheast 
##                           0.151019068 
##                       Region.fctrWest 
##                           0.091052386 
##                          Sex.fctrMale 
##                           0.229847065 
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
##  [1] ""                                     
##  [2] ".rnorm"                               
##  [3] "Age"                                  
##  [4] "Citizenship.fctrCitizen, Naturalized" 
##  [5] "Citizenship.fctrNon-Citizen"          
##  [6] "Education.fctrBachelor's degree"      
##  [7] "Education.fctrDoctorate degree"       
##  [8] "Education.fctrHigh school"            
##  [9] "Education.fctrMaster's degree"        
## [10] "Education.fctrNA.my"                  
## [11] "Education.fctrNo high school diploma" 
## [12] "Education.fctrProfessional degree"    
## [13] "Education.fctrSome college, no degree"
## [14] "Hispanic"                             
## [15] "Married.fctrMarried"                  
## [16] "Married.fctrNA.my"                    
## [17] "Married.fctrNever Married"            
## [18] "Married.fctrSeparated"                
## [19] "Married.fctrWidowed"                  
## [20] "PeopleInHousehold"                    
## [21] "Race.fctrAmerican Indian"             
## [22] "Race.fctrAsian"                       
## [23] "Race.fctrBlack"                       
## [24] "Race.fctrMultiracial"                 
## [25] "Race.fctrPacific Islander"            
## [26] "Region.fctrMidwest"                   
## [27] "Region.fctrNortheast"                 
## [28] "Region.fctrWest"                      
## [29] "Sex.fctrMale"                         
## [1] "myfit_mdl: train diagnostics complete: 1122.250000 secs"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                194     3181                201     600
##   Employed                 90    41243               1636    2166
##   Not.in.Labor.Force       36     6522               4301     288
##   Retired                  83     3387                 20   10123
##   Unemployed               13     2580                360     119
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.7241227      0.4749539      0.7209538      0.7272748      0.5850822 
## AccuracyPValue  McnemarPValue 
##      0.0000000      0.0000000 
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                 82     1169                 70     215
##   Employed                 50    15141                614     793
##   Not.in.Labor.Force       17     2429               1545     108
##   Retired                  26     1234                  5    3741
##   Unemployed                6      948                150      27
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.7229115      0.4729121      0.7176633      0.7281141      0.5850546 
## AccuracyPValue  McnemarPValue 
##      0.0000000      0.0000000 
## [1] "myfit_mdl: predict complete: 1124.230000 secs"
##                  id
## 1 All.X##rcv#glmnet
##                                                                                                               feats
## 1 Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              25                   1119.977                32.992
##   max.Accuracy.fit max.AccuracyLower.fit max.AccuracyUpper.fit
## 1        0.7235826             0.7209538             0.7272748
##   max.Kappa.fit max.Accuracy.OOB max.AccuracyLower.OOB
## 1     0.4737991        0.7229115             0.7176633
##   max.AccuracyUpper.OOB max.Kappa.OOB max.AccuracySD.fit max.KappaSD.fit
## 1             0.7281141     0.4729121        0.002280983     0.004205104
## [1] "myfit_mdl: exit: 1124.239000 secs"
# Check if other preProcess methods improve model performance
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_preProc", major.inc = FALSE,
                label.minor = "preProc")
##                  label step_major step_minor label_minor      bgn      end
## 3   fit.models_1_All.X          1          2      glmnet  153.880 1278.131
## 4 fit.models_1_preProc          1          3     preProc 1278.132       NA
##    elapsed
## 3 1124.251
## 4       NA
mdl_id <- orderBy(get_model_sel_frmla(), glb_models_df)[1, "id"]
indepVar <- trim(unlist(strsplit(glb_models_df[glb_models_df$id == mdl_id,
                                                      "feats"], "[,]")))
method <- tail(unlist(strsplit(mdl_id, "[.]")), 1)
mdl_id_pfx <- paste0(head(unlist(strsplit(mdl_id, "[.]")), -1), collapse = ".")
if (!is.null(glbObsFitOutliers[[mdl_id_pfx]])) {
    fitobs_df <- glbObsFit[!(glbObsFit[, glbFeatsId] %in%
                                     glbObsFitOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsFit) - nrow(fitobs_df)))
        print(setdiff(glbObsFit[, glbFeatsId], fitobs_df[, glbFeatsId]))
    
} else fitobs_df <- glbObsFit

for (prePr in glb_preproc_methods) {   
    # The operations are applied in this order: 
    #   Box-Cox/Yeo-Johnson transformation, centering, scaling, range, imputation, PCA, ICA then spatial sign.
    
    ret_lst <- myfit_mdl(mdl_specs_lst=myinit_mdl_specs_lst(mdl_specs_lst=list(
            id.prefix=mdl_id_pfx, 
            type=glb_model_type, tune.df=glbMdlTuneParams,
            trainControl.method="repeatedcv",
            trainControl.number=glb_rcv_n_folds,
            trainControl.repeats=glb_rcv_n_repeats,
            trainControl.classProbs = glb_is_classification,
            trainControl.summaryFunction = glbMdlMetricSummaryFn,
            train.metric = glbMdlMetricSummary, 
            train.maximize = glbMdlMetricMaximize,    
            train.method=method, train.preProcess=prePr)),
            indepVar=indepVar, rsp_var=glb_rsp_var, 
            fit_df=fitobs_df, OOB_df=glbObsOOB)
}            
    
    # If (All|RFE).X.glm is less accurate than Low.Cor.X.glm
    #   check NA coefficients & filter appropriate terms in indepVar
#     if (method == "glm") {
#         orig_glm <- glb_models_lst[[paste0(mdl_id, ".", model_method)]]$finalModel
#         orig_glm <- glb_models_lst[["All.X.glm"]]$finalModel; print(summary(orig_glm))
#         orig_glm <- glb_models_lst[["RFE.X.glm"]]$finalModel; print(summary(orig_glm))
#           require(car)
#           vif_orig_glm <- vif(orig_glm); print(vif_orig_glm)
#           # if vif errors out with "there are aliased coefficients in the model"
#               alias_orig_glm <- alias(orig_glm); alias_complete_orig_glm <- (alias_orig_glm$Complete > 0); alias_complete_orig_glm <- alias_complete_orig_glm[rowSums(alias_complete_orig_glm) > 0, colSums(alias_complete_orig_glm) > 0]; print(alias_complete_orig_glm)
#           print(vif_orig_glm[!is.na(vif_orig_glm) & (vif_orig_glm == Inf)])
#           print(which.max(vif_orig_glm))
#           print(sort(vif_orig_glm[vif_orig_glm >= 1.0e+03], decreasing=TRUE))
#           glbObsFit[c(1143, 3637, 3953, 4105), c("UniqueID", "Popular", "H.P.quandary", "Headline")]
#           glb_feats_df[glb_feats_df$id %in% grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE) | glb_feats_df$cor.high.X %in%    grep("[HSA]\\.chrs.n.log", glb_feats_df$id, value=TRUE), ]
#           all.equal(glbObsAll$S.chrs.uppr.n.log, glbObsAll$A.chrs.uppr.n.log)
#           cor(glbObsAll$S.T.herald, glbObsAll$S.T.tribun)
#           mydspObs(Abstract.contains="[Dd]iar", cols=("Abstract"), all=TRUE)
#           subset(glb_feats_df, cor.y.abs <= glb_feats_df[glb_feats_df$id == ".rnorm", "cor.y.abs"])
#         corxx_mtrx <- cor(data.matrix(glbObsAll[, setdiff(names(glbObsAll), myfind_chr_cols_df(glbObsAll))]), use="pairwise.complete.obs"); abs_corxx_mtrx <- abs(corxx_mtrx); diag(abs_corxx_mtrx) <- 0
#           which.max(abs_corxx_mtrx["S.T.tribun", ])
#           abs_corxx_mtrx["A.npnct08.log", "S.npnct08.log"]
#         step_glm <- step(orig_glm)
#     }
    # Since caret does not optimize rpart well
#     if (method == "rpart")
#         ret_lst <- myfit_mdl(mdl_id=paste0(mdl_id_pfx, ".cp.0"), model_method=method,
#                                 indepVar=indepVar,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,        
#             n_cv_folds=0, tune_models_df=data.frame(parameter="cp", min=0.0, max=0.0, by=0.1))

# User specified
#   Ensure at least 2 vars in each regression; else varImp crashes
# sav_models_lst <- glb_models_lst; sav_models_df <- glb_models_df; sav_featsimp_df <- glb_featsimp_df; all.equal(sav_featsimp_df, glb_featsimp_df)
# glb_models_lst <- sav_models_lst; glb_models_df <- sav_models_df; glm_featsimp_df <- sav_featsimp_df

    # easier to exclude features
# require(gdata) # needed for trim
# mdl_id <- "";
# indepVar <- head(subset(glb_models_df, grepl("All\\.X\\.", mdl_id), select=feats)
#                         , 1)[, "feats"]
# indepVar <- trim(unlist(strsplit(indepVar, "[,]")))
# indepVar <- setdiff(indepVar, ".rnorm")

    # easier to include features
#stop(here"); sav_models_df <- glb_models_df; glb_models_df <- sav_models_df
# !_sp
# mdl_id <- "csm"; indepVar <- c(NULL
#     ,"prdline.my.fctr", "prdline.my.fctr:.clusterid.fctr"
#     ,"prdline.my.fctr*biddable"
#     #,"prdline.my.fctr*startprice.log"
#     #,"prdline.my.fctr*startprice.diff"    
#     ,"prdline.my.fctr*condition.fctr"
#     ,"prdline.my.fctr*D.terms.post.stop.n"
#     #,"prdline.my.fctr*D.terms.post.stem.n"
#     ,"prdline.my.fctr*cellular.fctr"    
# #    ,"<feat1>:<feat2>"
#                                            )
# for (method in glbMdlMethods) {
#     ret_lst <- myfit_mdl(mdl_id=mdl_id, model_method=method,
#                                 indepVar=indepVar,
#                                 model_type=glb_model_type,
#                                 rsp_var=glb_rsp_var,
#                                 fit_df=glbObsFit, OOB_df=glbObsOOB,
#                     n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams)
#     csm_mdl_id <- paste0(mdl_id, ".", method)
#     csm_featsimp_df <- myget_feats_importance(glb_models_lst[[paste0(mdl_id, ".",
#                                                                      method)]]);               print(head(csm_featsimp_df))
# }
###

# Ntv.1.lm <- lm(reformulate(indepVar, glb_rsp_var), glbObsTrn); print(summary(Ntv.1.lm))

#glb_models_df[, "max.Accuracy.OOB", FALSE]
#varImp(glb_models_lst[["Low.cor.X.glm"]])
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.2.glm"]])$imp)
#orderBy(~ -Overall, varImp(glb_models_lst[["All.X.3.glm"]])$imp)
#glb_feats_df[grepl("npnct28", glb_feats_df$id), ]

    # User specified bivariate models
#     indepVar_lst <- list()
#     for (feat in setdiff(names(glbObsFit), 
#                          union(glb_rsp_var, glbFeatsExclude)))
#         indepVar_lst[["feat"]] <- feat

    # User specified combinatorial models
#     indepVar_lst <- list()
#     combn_mtrx <- combn(c("<feat1_name>", "<feat2_name>", "<featn_name>"), 
#                           <num_feats_to_choose>)
#     for (combn_ix in 1:ncol(combn_mtrx))
#         #print(combn_mtrx[, combn_ix])
#         indepVar_lst[[combn_ix]] <- combn_mtrx[, combn_ix]
    
    # template for myfit_mdl
    #   rf is hard-coded in caret to recognize only Accuracy / Kappa evaluation metrics
    #       only for OOB in trainControl ?
    
#     ret_lst <- myfit_mdl_fn(mdl_id=paste0(mdl_id_pfx, ""), model_method=method,
#                             indepVar=indepVar,
#                             rsp_var=glb_rsp_var,
#                             fit_df=glbObsFit, OOB_df=glbObsOOB,
#                             n_cv_folds=glb_rcv_n_folds, tune_models_df=glbMdlTuneParams,
#                             model_loss_mtrx=glbMdlMetric_terms,
#                             model_summaryFunction=glbMdlMetricSummaryFn,
#                             model_metric=glbMdlMetricSummary,
#                             model_metric_maximize=glbMdlMetricMaximize)

# Simplify a model
# fit_df <- glbObsFit; glb_mdl <- step(<complex>_mdl)

# Non-caret models
#     rpart_area_mdl <- rpart(reformulate("Area", response=glb_rsp_var), 
#                                data=glbObsFit, #method="class", 
#                                control=rpart.control(cp=0.12),
#                            parms=list(loss=glbMdlMetric_terms))
#     print("rpart_sel_wlm_mdl"); prp(rpart_sel_wlm_mdl)
# 

print(glb_models_df)
##                                                    id
## MFO###myMFO_classfr               MFO###myMFO_classfr
## Random###myrandom_classfr   Random###myrandom_classfr
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart             Max.cor.Y##rcv#rpart
## All.X##rcv#glmnet                   All.X##rcv#glmnet
##                                                                                                                                        feats
## MFO###myMFO_classfr                                                                                                                   .rnorm
## Random###myrandom_classfr                                                                                                             .rnorm
## Max.cor.Y.rcv.1X1###glmnet                                                                                                  Age,Married.fctr
## Max.cor.Y##rcv#rpart                                                                                                        Age,Married.fctr
## All.X##rcv#glmnet          Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold
##                            max.nTuningRuns min.elapsedtime.everything
## MFO###myMFO_classfr                      0                      0.484
## Random###myrandom_classfr                0                      0.336
## Max.cor.Y.rcv.1X1###glmnet               0                     12.169
## Max.cor.Y##rcv#rpart                     5                     14.705
## All.X##rcv#glmnet                       25                   1119.977
##                            min.elapsedtime.final max.Accuracy.fit
## MFO###myMFO_classfr                        0.020        0.5850822
## Random###myrandom_classfr                  0.017        0.3996604
## Max.cor.Y.rcv.1X1###glmnet                10.348        0.6842487
## Max.cor.Y##rcv#rpart                       0.399        0.7264431
## All.X##rcv#glmnet                         32.992        0.7235826
##                            max.AccuracyLower.fit max.AccuracyUpper.fit
## MFO###myMFO_classfr                    0.5815957             0.5885624
## Random###myrandom_classfr              0.3962012             0.4031271
## Max.cor.Y.rcv.1X1###glmnet             0.6809553             0.6875283
## Max.cor.Y##rcv#rpart                   0.7239458             0.7302455
## All.X##rcv#glmnet                      0.7209538             0.7272748
##                            max.Kappa.fit max.Accuracy.OOB
## MFO###myMFO_classfr          0.000000000        0.5850546
## Random###myrandom_classfr    0.001664263        0.3991540
## Max.cor.Y.rcv.1X1###glmnet   0.344662905        0.6859711
## Max.cor.Y##rcv#rpart         0.477125106        0.7276701
## All.X##rcv#glmnet            0.473799092        0.7229115
##                            max.AccuracyLower.OOB max.AccuracyUpper.OOB
## MFO###myMFO_classfr                    0.5792951             0.5907967
## Random###myrandom_classfr              0.3934484             0.4048804
## Max.cor.Y.rcv.1X1###glmnet             0.6805339             0.6913702
## Max.cor.Y##rcv#rpart                   0.7224493             0.7328442
## All.X##rcv#glmnet                      0.7176633             0.7281141
##                            max.Kappa.OOB max.AccuracySD.fit
## MFO###myMFO_classfr         0.0000000000                 NA
## Random###myrandom_classfr   0.0006568311                 NA
## Max.cor.Y.rcv.1X1###glmnet  0.3481272164                 NA
## Max.cor.Y##rcv#rpart        0.4783438508        0.002327336
## All.X##rcv#glmnet           0.4729121383        0.002280983
##                            max.KappaSD.fit
## MFO###myMFO_classfr                     NA
## Random###myrandom_classfr               NA
## Max.cor.Y.rcv.1X1###glmnet              NA
## Max.cor.Y##rcv#rpart           0.005671842
## All.X##rcv#glmnet              0.004205104
rm(ret_lst)
fit.models_1_chunk_df <- 
    myadd_chunk(fit.models_1_chunk_df, "fit.models_1_end", major.inc = FALSE,
                label.minor = "teardown")
##                  label step_major step_minor label_minor      bgn      end
## 4 fit.models_1_preProc          1          3     preProc 1278.132 1278.187
## 5     fit.models_1_end          1          4    teardown 1278.188       NA
##   elapsed
## 4   0.055
## 5      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc = FALSE)
##         label step_major step_minor label_minor      bgn      end  elapsed
## 17 fit.models          8          1           1  153.030 1278.195 1125.166
## 18 fit.models          8          2           2 1278.196       NA       NA
fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "setup")
##              label step_major step_minor label_minor      bgn end elapsed
## 1 fit.models_2_bgn          1          0       setup 1279.567  NA      NA
plt_models_df <- glb_models_df[, -grep("SD|Upper|Lower", names(glb_models_df))]
for (var in grep("^min.", names(plt_models_df), value=TRUE)) {
    plt_models_df[, sub("min.", "inv.", var)] <- 
        #ifelse(all(is.na(tmp <- plt_models_df[, var])), NA, 1.0 / tmp)
        1.0 / plt_models_df[, var]
    plt_models_df <- plt_models_df[ , -grep(var, names(plt_models_df))]
}
print(plt_models_df)
##                                                    id
## MFO###myMFO_classfr               MFO###myMFO_classfr
## Random###myrandom_classfr   Random###myrandom_classfr
## Max.cor.Y.rcv.1X1###glmnet Max.cor.Y.rcv.1X1###glmnet
## Max.cor.Y##rcv#rpart             Max.cor.Y##rcv#rpart
## All.X##rcv#glmnet                   All.X##rcv#glmnet
##                                                                                                                                        feats
## MFO###myMFO_classfr                                                                                                                   .rnorm
## Random###myrandom_classfr                                                                                                             .rnorm
## Max.cor.Y.rcv.1X1###glmnet                                                                                                  Age,Married.fctr
## Max.cor.Y##rcv#rpart                                                                                                        Age,Married.fctr
## All.X##rcv#glmnet          Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold
##                            max.nTuningRuns max.Accuracy.fit max.Kappa.fit
## MFO###myMFO_classfr                      0        0.5850822   0.000000000
## Random###myrandom_classfr                0        0.3996604   0.001664263
## Max.cor.Y.rcv.1X1###glmnet               0        0.6842487   0.344662905
## Max.cor.Y##rcv#rpart                     5        0.7264431   0.477125106
## All.X##rcv#glmnet                       25        0.7235826   0.473799092
##                            max.Accuracy.OOB max.Kappa.OOB
## MFO###myMFO_classfr               0.5850546  0.0000000000
## Random###myrandom_classfr         0.3991540  0.0006568311
## Max.cor.Y.rcv.1X1###glmnet        0.6859711  0.3481272164
## Max.cor.Y##rcv#rpart              0.7276701  0.4783438508
## All.X##rcv#glmnet                 0.7229115  0.4729121383
##                            inv.elapsedtime.everything
## MFO###myMFO_classfr                      2.0661157025
## Random###myrandom_classfr                2.9761904762
## Max.cor.Y.rcv.1X1###glmnet               0.0821760210
## Max.cor.Y##rcv#rpart                     0.0680040802
## All.X##rcv#glmnet                        0.0008928755
##                            inv.elapsedtime.final
## MFO###myMFO_classfr                  50.00000000
## Random###myrandom_classfr            58.82352941
## Max.cor.Y.rcv.1X1###glmnet            0.09663703
## Max.cor.Y##rcv#rpart                  2.50626566
## All.X##rcv#glmnet                     0.03031038
# print(myplot_radar(radar_inp_df=plt_models_df))
# print(myplot_radar(radar_inp_df=subset(plt_models_df, 
#         !(mdl_id %in% grep("random|MFO", plt_models_df$id, value=TRUE)))))

# Compute CI for <metric>SD
glb_models_df <- mutate(glb_models_df, 
                max.df = ifelse(max.nTuningRuns > 1, max.nTuningRuns - 1, NA),
                min.sd2ci.scaler = ifelse(is.na(max.df), NA, qt(0.975, max.df)))
for (var in grep("SD", names(glb_models_df), value=TRUE)) {
    # Does CI alredy exist ?
    var_components <- unlist(strsplit(var, "SD"))
    varActul <- paste0(var_components[1],          var_components[2])
    varUpper <- paste0(var_components[1], "Upper", var_components[2])
    varLower <- paste0(var_components[1], "Lower", var_components[2])
    if (varUpper %in% names(glb_models_df)) {
        warning(varUpper, " already exists in glb_models_df")
        # Assuming Lower also exists
        next
    }    
    print(sprintf("var:%s", var))
    # CI is dependent on sample size in t distribution; df=n-1
    glb_models_df[, varUpper] <- glb_models_df[, varActul] + 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
    glb_models_df[, varLower] <- glb_models_df[, varActul] - 
        glb_models_df[, "min.sd2ci.scaler"] * glb_models_df[, var]
}
## Warning: max.AccuracyUpper.fit already exists in glb_models_df
## [1] "var:max.KappaSD.fit"
# Plot metrics with CI
plt_models_df <- glb_models_df[, "id", FALSE]
pltCI_models_df <- glb_models_df[, "id", FALSE]
for (var in grep("Upper", names(glb_models_df), value=TRUE)) {
    var_components <- unlist(strsplit(var, "Upper"))
    col_name <- unlist(paste(var_components, collapse=""))
    plt_models_df[, col_name] <- glb_models_df[, col_name]
    for (name in paste0(var_components[1], c("Upper", "Lower"), var_components[2]))
        pltCI_models_df[, name] <- glb_models_df[, name]
}

build_statsCI_data <- function(plt_models_df) {
    mltd_models_df <- melt(plt_models_df, id.vars="id")
    mltd_models_df$data <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) tail(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), "[.]")), 1))
    mltd_models_df$label <- sapply(1:nrow(mltd_models_df), 
        function(row_ix) head(unlist(strsplit(as.character(
            mltd_models_df[row_ix, "variable"]), 
            paste0(".", mltd_models_df[row_ix, "data"]))), 1))
    #print(mltd_models_df)
    
    return(mltd_models_df)
}
mltd_models_df <- build_statsCI_data(plt_models_df)

mltdCI_models_df <- melt(pltCI_models_df, id.vars="id")
for (row_ix in 1:nrow(mltdCI_models_df)) {
    for (type in c("Upper", "Lower")) {
        if (length(var_components <- unlist(strsplit(
                as.character(mltdCI_models_df[row_ix, "variable"]), type))) > 1) {
            #print(sprintf("row_ix:%d; type:%s; ", row_ix, type))
            mltdCI_models_df[row_ix, "label"] <- var_components[1]
            mltdCI_models_df[row_ix, "data"] <- 
                unlist(strsplit(var_components[2], "[.]"))[2]
            mltdCI_models_df[row_ix, "type"] <- type
            break
        }
    }    
}
wideCI_models_df <- reshape(subset(mltdCI_models_df, select=-variable), 
                            timevar="type", 
        idvar=setdiff(names(mltdCI_models_df), c("type", "value", "variable")), 
                            direction="wide")
#print(wideCI_models_df)
mrgdCI_models_df <- merge(wideCI_models_df, mltd_models_df, all.x=TRUE)
#print(mrgdCI_models_df)

# Merge stats back in if CIs don't exist
goback_vars <- c()
for (var in unique(mltd_models_df$label)) {
    for (type in unique(mltd_models_df$data)) {
        var_type <- paste0(var, ".", type)
        # if this data is already present, next
        if (var_type %in% unique(paste(mltd_models_df$label, mltd_models_df$data,
                                       sep=".")))
            next
        #print(sprintf("var_type:%s", var_type))
        goback_vars <- c(goback_vars, var_type)
    }
}

if (length(goback_vars) > 0) {
    mltd_goback_df <- build_statsCI_data(glb_models_df[, c("id", goback_vars)])
    mltd_models_df <- rbind(mltd_models_df, mltd_goback_df)
}

# mltd_models_df <- merge(mltd_models_df, glb_models_df[, c("id", "model_method")], 
#                         all.x=TRUE)

png(paste0(glbOut$pfx, "models_bar.png"), width=480*3, height=480*2)
#print(gp <- myplot_bar(mltd_models_df, "id", "value", colorcol_name="model_method") + 
print(gp <- myplot_bar(df=mltd_models_df, xcol_name="id", ycol_names="value") + 
        geom_errorbar(data=mrgdCI_models_df, 
            mapping=aes(x=mdl_id, ymax=value.Upper, ymin=value.Lower), width=0.5) + 
          facet_grid(label ~ data, scales="free") + 
          theme(axis.text.x = element_text(angle = 90,vjust = 0.5)))
## Warning: Removed 3 rows containing missing values (geom_errorbar).
dev.off()
## quartz_off_screen 
##                 2
print(gp)
## Warning: Removed 3 rows containing missing values (geom_errorbar).

dsp_models_cols <- c("id", 
                    glbMdlMetricsEval[glbMdlMetricsEval %in% names(glb_models_df)],
                    grep("opt.", names(glb_models_df), fixed = TRUE, value = TRUE)) 
# if (glb_is_classification && glb_is_binomial) 
#     dsp_models_cols <- c(dsp_models_cols, "opt.prob.threshold.OOB")
print(dsp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)[, dsp_models_cols])
##                           id max.Accuracy.OOB max.Kappa.OOB
## 4       Max.cor.Y##rcv#rpart        0.7276701  0.4783438508
## 5          All.X##rcv#glmnet        0.7229115  0.4729121383
## 3 Max.cor.Y.rcv.1X1###glmnet        0.6859711  0.3481272164
## 1        MFO###myMFO_classfr        0.5850546  0.0000000000
## 2  Random###myrandom_classfr        0.3991540  0.0006568311
# print(myplot_radar(radar_inp_df = dsp_models_df))
print("Metrics used for model selection:"); print(get_model_sel_frmla())
## [1] "Metrics used for model selection:"
## ~-max.Accuracy.OOB - max.Kappa.OOB
## <environment: 0x7fc5577bbc28>
print(sprintf("Best model id: %s", dsp_models_df[1, "id"]))
## [1] "Best model id: Max.cor.Y##rcv#rpart"
glb_get_predictions <- function(df, mdl_id, rsp_var, prob_threshold_def=NULL, verbose=FALSE) {
    mdl <- glb_models_lst[[mdl_id]]
    
    clmnNames <- mygetPredictIds(rsp_var, mdl_id)
    predct_var_name <- clmnNames$value        
    predct_prob_var_name <- clmnNames$prob
    predct_accurate_var_name <- clmnNames$is.acc
    predct_error_var_name <- clmnNames$err
    predct_erabs_var_name <- clmnNames$err.abs

    if (glb_is_regression) {
        df[, predct_var_name] <- predict(mdl, newdata=df, type="raw")
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
                  facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] - df[, glb_rsp_var]
        if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="auto"))
        if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
                  #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
                  stat_smooth(method="glm"))
        
        df[, predct_erabs_var_name] <- abs(df[, predct_error_var_name])
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }

    if (glb_is_classification && glb_is_binomial) {
        prob_threshold <- glb_models_df[glb_models_df$id == mdl_id, 
                                        "opt.prob.threshold.OOB"]
        if (is.null(prob_threshold) || is.na(prob_threshold)) {
            warning("Using default probability threshold: ", prob_threshold_def)
            if (is.null(prob_threshold <- prob_threshold_def))
                stop("Default probability threshold is NULL")
        }
        
        df[, predct_prob_var_name] <- predict(mdl, newdata = df, type = "prob")[, 2]
        df[, predct_var_name] <- 
                factor(levels(df[, glb_rsp_var])[
                    (df[, predct_prob_var_name] >=
                        prob_threshold) * 1 + 1], levels(df[, glb_rsp_var]))
    
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_var_name) + 
#                   facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))

        df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
#         if (verbose) print(myplot_scatter(df, predct_var_name, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="auto"))
#         if (verbose) print(myplot_scatter(df, glb_rsp_var, predct_error_var_name) + 
#                   #facet_wrap(reformulate(glbFeatsCategory), scales = "free") + 
#                   stat_smooth(method="glm"))
        
        # if prediction is a TP (true +ve), measure distance from 1.0
        tp <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[tp, predct_erabs_var_name] <- abs(1 - df[tp, predct_prob_var_name])
        #rowIx <- which.max(df[tp, predct_erabs_var_name]); df[tp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a TN (true -ve), measure distance from 0.0
        tn <- which((df[, predct_var_name] == df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[tn, predct_erabs_var_name] <- abs(0 - df[tn, predct_prob_var_name])
        #rowIx <- which.max(df[tn, predct_erabs_var_name]); df[tn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FP (flse +ve), measure distance from 0.0
        fp <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[2]))
        df[fp, predct_erabs_var_name] <- abs(0 - df[fp, predct_prob_var_name])
        #rowIx <- which.max(df[fp, predct_erabs_var_name]); df[fp, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]
        
        # if prediction is a FN (flse -ve), measure distance from 1.0
        fn <- which((df[, predct_var_name] != df[, glb_rsp_var]) &
                    (df[, predct_var_name] == levels(df[, glb_rsp_var])[1]))
        df[fn, predct_erabs_var_name] <- abs(1 - df[fn, predct_prob_var_name])
        #rowIx <- which.max(df[fn, predct_erabs_var_name]); df[fn, c(glbFeatsId, glb_rsp_var, predct_var_name, predct_prob_var_name, predct_erabs_var_name)][rowIx, ]

        
        if (verbose) print(head(orderBy(reformulate(c("-", predct_erabs_var_name)), df)))
        
        df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])
    }    
    
    if (glb_is_classification && !glb_is_binomial) {
        df[, predct_var_name] <- predict(mdl, newdata = df, type = "raw")
        probCls <- predict(mdl, newdata = df, type = "prob")        
        df[, predct_prob_var_name] <- NA
        for (cls in names(probCls)) {
            mask <- (df[, predct_var_name] == cls)
            df[mask, predct_prob_var_name] <- probCls[mask, cls]
        }    
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            fill_col_name = predct_var_name))
        if (verbose) print(myplot_histogram(df, predct_prob_var_name, 
                                            facet_frmla = paste0("~", glb_rsp_var)))
        
        # if prediction is erroneous, measure predicted class prob from actual class prob
        if (all(is.na(df[, glb_rsp_var]))) {
            df[, predct_error_var_name] <- NA
            df[, predct_erabs_var_name] <- NA 
            df[, predct_accurate_var_name] <- NA
        } else {
            df[, predct_error_var_name] <- df[, predct_var_name] != df[, glb_rsp_var]
            df[, predct_erabs_var_name] <- 0
            for (cls in names(probCls)) {
                mask <- (df[, glb_rsp_var] == cls) & (df[, predct_error_var_name])
                df[mask, predct_erabs_var_name] <- probCls[mask, cls]
            }    
            df[, predct_accurate_var_name] <- (df[, glb_rsp_var] == df[, predct_var_name])            
        }
    }

    return(df)
}    

#stop(here"); glb2Sav(); glbObsAll <- savObsAll; glbObsTrn <- savObsTrn; glbObsFit <- savObsFit; glbObsOOB <- savObsOOB; sav_models_df <- glb_models_df; glb_models_df <- sav_models_df; glb_featsimp_df <- sav_featsimp_df    

myget_category_stats <- function(obs_df, mdl_id, label) {
    require(dplyr)
    require(lazyeval)
    
    predct_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$value        
    predct_error_var_name <- mygetPredictIds(glb_rsp_var, mdl_id)$err.abs
    
    if (!predct_var_name %in% names(obs_df))
        obs_df <- glb_get_predictions(obs_df, mdl_id, glb_rsp_var)
    
    tmp_obs_df <- obs_df[, c(glbFeatsCategory, glb_rsp_var, 
                             predct_var_name, predct_error_var_name)]
#     tmp_obs_df <- obs_df %>%
#         dplyr::select_(glbFeatsCategory, glb_rsp_var, predct_var_name, predct_error_var_name) 
    #dplyr::rename(startprice.log10.predict.RFE.X.glmnet.err=error_abs_OOB)
    names(tmp_obs_df)[length(names(tmp_obs_df))] <- paste0("err.abs.", label)
    
    ret_ctgry_df <- tmp_obs_df %>%
        dplyr::group_by_(glbFeatsCategory) %>%
        dplyr::summarise_(#interp(~sum(abs(var)), var=as.name(glb_rsp_var)), 
            interp(~sum(var), var=as.name(paste0("err.abs.", label))), 
            interp(~mean(var), var=as.name(paste0("err.abs.", label))),
            interp(~n()))
    names(ret_ctgry_df) <- c(glbFeatsCategory, 
                             #paste0(glb_rsp_var, ".abs.", label, ".sum"),
                             paste0("err.abs.", label, ".sum"),                             
                             paste0("err.abs.", label, ".mean"), 
                             paste0(".n.", label))
    ret_ctgry_df <- dplyr::ungroup(ret_ctgry_df)
    #colSums(ret_ctgry_df[, -grep(glbFeatsCategory, names(ret_ctgry_df))])
    
    return(ret_ctgry_df)    
}
#print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))

if (!is.null(glb_mdl_ensemble)) {
    fit.models_2_chunk_df <- myadd_chunk(fit.models_2_chunk_df, 
                            paste0("fit.models_2_", mdl_id_pfx), major.inc = TRUE, 
                                                label.minor = "ensemble")
    
    mdl_id_pfx <- "Ensemble"

    if (#(glb_is_regression) | 
        ((glb_is_classification) & (!glb_is_binomial)))
        stop("Ensemble models not implemented yet for multinomial classification")
    
    mygetEnsembleAutoMdlIds <- function() {
        tmp_models_df <- orderBy(get_model_sel_frmla(), glb_models_df)
        row.names(tmp_models_df) <- tmp_models_df$id
        mdl_threshold_pos <- 
            min(which(grepl("MFO|Random|Baseline", tmp_models_df$id))) - 1
        mdlIds <- tmp_models_df$id[1:mdl_threshold_pos]
        return(mdlIds[!grepl("Ensemble", mdlIds)])
    }
    
    if (glb_mdl_ensemble == "auto") {
        glb_mdl_ensemble <- mygetEnsembleAutoMdlIds()
        mdl_id_pfx <- paste0(mdl_id_pfx, ".auto")        
    } else if (grepl("^%<d-%", glb_mdl_ensemble)) {
        glb_mdl_ensemble <- eval(parse(text =
                        str_trim(unlist(strsplit(glb_mdl_ensemble, "%<d-%"))[2])))
    }
    
    for (mdl_id in glb_mdl_ensemble) {
        if (!(mdl_id %in% names(glb_models_lst))) {
            warning("Model ", mdl_id, " in glb_model_ensemble not found !")
            next
        }
        glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id, glb_rsp_var)
        glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id, glb_rsp_var)
    }
    
#mdl_id_pfx <- "Ensemble.RFE"; mdlId <- paste0(mdl_id_pfx, ".glmnet")
#glb_mdl_ensemble <- gsub(mygetPredictIds$value, "", grep("RFE\\.X\\.(?!Interact)", row.names(glb_featsimp_df), perl = TRUE, value = TRUE), fixed = TRUE)
#varImp(glb_models_lst[[mdlId]])
    
#cor_df <- data.frame(cor=cor(glbObsFit[, glb_rsp_var], glbObsFit[, paste(mygetPredictIds$value, glb_mdl_ensemble)], use="pairwise.complete.obs"))
#glbObsFit <- glb_get_predictions(df=glbObsFit, "Ensemble.glmnet", glb_rsp_var);print(colSums((ctgry_df <- myget_category_stats(obs_df=glbObsFit, mdl_id="Ensemble.glmnet", label="fit"))[, -grep(glbFeatsCategory, names(ctgry_df))]))
    
    ### bid0_sp
    #  Better than MFO; models.n=28; min.RMSE.fit=0.0521233; err.abs.fit.sum=7.3631895
    #  old: Top x from auto; models.n= 5; min.RMSE.fit=0.06311047; err.abs.fit.sum=9.5937080
    #  RFE only ;       models.n=16; min.RMSE.fit=0.05148588; err.abs.fit.sum=7.2875091
    #  RFE subset only ;models.n= 5; min.RMSE.fit=0.06040702; err.abs.fit.sum=9.059088
    #  RFE subset only ;models.n= 9; min.RMSE.fit=0.05933167; err.abs.fit.sum=8.7421288
    #  RFE subset only ;models.n=15; min.RMSE.fit=0.0584607; err.abs.fit.sum=8.5902066
    #  RFE subset only ;models.n=17; min.RMSE.fit=0.05496899; err.abs.fit.sum=8.0170431
    #  RFE subset only ;models.n=18; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    #  RFE subset only ;models.n=16; min.RMSE.fit=0.05441577; err.abs.fit.sum=7.837223
    ### bid0_sp
    ### bid1_sp
    # "auto"; err.abs.fit.sum=76.699774; min.RMSE.fit=0.2186429
    # "RFE.X.*"; err.abs.fit.sum=; min.RMSE.fit=0.221114
    ### bid1_sp

    indepVar <- paste(mygetPredictIds(glb_rsp_var)$value, glb_mdl_ensemble, sep = "")
    if (glb_is_classification)
        indepVar <- paste(indepVar, ".prob", sep = "")
    # Some models in glb_mdl_ensemble might not be fitted e.g. RFE.X.Interact
    indepVar <- intersect(indepVar, names(glbObsFit))
    
#     indepVar <- grep(mygetPredictIds(glb_rsp_var)$value, names(glbObsFit), fixed=TRUE, value=TRUE)
#     if (glb_is_regression)
#         indepVar <- indepVar[!grepl("(err\\.abs|accurate)$", indepVar)]
#     if (glb_is_classification && glb_is_binomial)
#         indepVar <- grep("prob$", indepVar, value=TRUE) else
#         indepVar <- indepVar[!grepl("err$", indepVar)]

    #rfe_fit_ens_results <- myrun_rfe(glbObsFit, indepVar)
    
    for (method in c("glm", "glmnet")) {
        for (trainControlMethod in 
             c("boot", "boot632", "cv", "repeatedcv"
               #, "LOOCV" # tuneLength * nrow(fitDF)
               , "LGOCV", "adaptive_cv"
               #, "adaptive_boot"  #error: adaptive$min should be less than 3 
               #, "adaptive_LGOCV" #error: adaptive$min should be less than 3 
               )) {
            #sav_models_df <- glb_models_df; all.equal(sav_models_df, glb_models_df)
            #glb_models_df <- sav_models_df; print(glb_models_df$id)
                
            if ((method == "glm") && (trainControlMethod != "repeatedcv"))
                # glm used only to identify outliers
                next
            
            ret_lst <- myfit_mdl(
                mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = paste0(mdl_id_pfx, ".", trainControlMethod), 
                    type = glb_model_type, tune.df = NULL,
                    trainControl.method = trainControlMethod,
                    trainControl.number = glb_rcv_n_folds,
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method)),
                indepVar = indepVar, rsp_var = glb_rsp_var, 
                fit_df = glbObsFit, OOB_df = glbObsOOB)
        }
    }
    dsp_models_df <- get_dsp_models_df()
}

if (is.null(glb_sel_mdl_id)) 
    glb_sel_mdl_id <- dsp_models_df[1, "id"] else 
    print(sprintf("User specified selection: %s", glb_sel_mdl_id))   
## [1] "User specified selection: All.X##rcv#glmnet"
myprint_mdl(glb_sel_mdl <- glb_models_lst[[glb_sel_mdl_id]])

##             Length Class      Mode     
## a0          380    -none-     numeric  
## beta          5    -none-     list     
## dfmat       380    -none-     numeric  
## df           76    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       76    -none-     numeric  
## dev.ratio    76    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    5    -none-     character
## grouped       1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames       28    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     5    -none-     character
## [1] "min lambda > lambdaOpt:"
## [1] "class: Disabled:"
##                                       
##                          -0.682133676 
##                                .rnorm 
##                           0.016236821 
##                                   Age 
##                           0.052704231 
##  Citizenship.fctrCitizen, Naturalized 
##                          -0.505511515 
##           Citizenship.fctrNon-Citizen 
##                          -0.860459043 
##       Education.fctrBachelor's degree 
##                          -0.629820356 
##        Education.fctrDoctorate degree 
##                          -0.626569025 
##             Education.fctrHigh school 
##                           0.362734617 
##         Education.fctrMaster's degree 
##                          -0.868888624 
##  Education.fctrNo high school diploma 
##                           1.064677342 
##     Education.fctrProfessional degree 
##                          -0.757369329 
## Education.fctrSome college, no degree 
##                           0.115647622 
##                   Married.fctrMarried 
##                          -0.857965891 
##                 Married.fctrSeparated 
##                           0.160275744 
##                     PeopleInHousehold 
##                          -0.016579180 
##              Race.fctrAmerican Indian 
##                           0.009019554 
##                        Race.fctrAsian 
##                          -0.072868661 
##                        Race.fctrBlack 
##                           0.310408699 
##                  Race.fctrMultiracial 
##                           0.092364638 
##             Race.fctrPacific Islander 
##                           0.275381398 
##                    Region.fctrMidwest 
##                          -0.071696043 
##                  Region.fctrNortheast 
##                          -0.016321483 
##                       Region.fctrWest 
##                          -0.105253659 
## [1] "class: Employed:"
##                                       
##                            4.07376570 
##                                .rnorm 
##                            0.01129780 
##  Citizenship.fctrCitizen, Naturalized 
##                            0.08291596 
##           Citizenship.fctrNon-Citizen 
##                            0.07695471 
##       Education.fctrBachelor's degree 
##                            0.15279080 
##        Education.fctrDoctorate degree 
##                            0.76855035 
##             Education.fctrHigh school 
##                           -0.45606953 
##         Education.fctrMaster's degree 
##                            0.25793173 
##  Education.fctrNo high school diploma 
##                           -0.85274987 
##     Education.fctrProfessional degree 
##                            0.53560074 
## Education.fctrSome college, no degree 
##                           -0.21721324 
##                              Hispanic 
##                            0.05415627 
##             Married.fctrNever Married 
##                           -0.20637501 
##                   Married.fctrWidowed 
##                           -0.11773377 
##              Race.fctrAmerican Indian 
##                           -0.36911791 
##                        Race.fctrBlack 
##                           -0.20263429 
##                  Race.fctrMultiracial 
##                           -0.12817419 
##             Race.fctrPacific Islander 
##                           -0.15995753 
##                    Region.fctrMidwest 
##                            0.14673165 
##                  Region.fctrNortheast 
##                            0.08782864 
##                          Sex.fctrMale 
##                            0.22191720 
## [1] "class: Not.in.Labor.Force:"
##                                       
##                            3.24612651 
##                                   Age 
##                           -0.04130075 
##  Citizenship.fctrCitizen, Naturalized 
##                            0.04137445 
##           Citizenship.fctrNon-Citizen 
##                            0.15887442 
##         Education.fctrMaster's degree 
##                           -0.04074203 
##  Education.fctrNo high school diploma 
##                            0.96791390 
## Education.fctrSome college, no degree 
##                            0.23005093 
##                              Hispanic 
##                           -0.10370630 
##                   Married.fctrMarried 
##                            0.25953648 
##             Married.fctrNever Married 
##                            0.33375203 
##                 Married.fctrSeparated 
##                           -0.03752998 
##                   Married.fctrWidowed 
##                            0.58309739 
##                     PeopleInHousehold 
##                            0.14682379 
##                        Race.fctrAsian 
##                            0.43940282 
##                        Race.fctrBlack 
##                           -0.09106900 
##                  Race.fctrMultiracial 
##                            0.05427560 
##                    Region.fctrMidwest 
##                           -0.14995281 
##                          Sex.fctrMale 
##                           -0.71644104 
## [1] "class: Retired:"
##                                                                    .rnorm 
##                         -7.766237327                         -0.016588779 
##                                  Age Citizenship.fctrCitizen, Naturalized 
##                          0.180449160                         -0.210603156 
##          Citizenship.fctrNon-Citizen      Education.fctrBachelor's degree 
##                         -0.291485719                          0.041172954 
##       Education.fctrDoctorate degree            Education.fctrHigh school 
##                          0.034833709                         -0.076053875 
##        Education.fctrMaster's degree                  Married.fctrMarried 
##                          0.235914499                          0.408448441 
##            Married.fctrNever Married                Married.fctrSeparated 
##                         -0.049324597                         -0.215449376 
##                  Married.fctrWidowed                    PeopleInHousehold 
##                          0.527580786                         -0.159180446 
##             Race.fctrAmerican Indian                       Race.fctrAsian 
##                         -0.180429213                          0.149154928 
##                 Race.fctrMultiracial            Race.fctrPacific Islander 
##                         -0.112375180                         -0.184683057 
##                 Region.fctrNortheast                      Region.fctrWest 
##                         -0.001068302                          0.080242502 
##                         Sex.fctrMale 
##                         -0.112094049 
## [1] "class: Unemployed:"
##                                       
##                           1.128478797 
##                                   Age 
##                          -0.003594189 
##             Education.fctrHigh school 
##                           0.006293782 
##  Education.fctrNo high school diploma 
##                          -0.117670195 
## Education.fctrSome college, no degree 
##                          -0.003394560 
##                              Hispanic 
##                           0.171124677 
##                   Married.fctrMarried 
##                          -0.539803262 
##             Married.fctrNever Married 
##                           0.026250406 
##                 Married.fctrSeparated 
##                           0.056433648 
##                   Married.fctrWidowed 
##                          -0.113801986 
##                     PeopleInHousehold 
##                           0.071712840 
##              Race.fctrAmerican Indian 
##                           0.226698090 
##                        Race.fctrAsian 
##                          -0.055242748 
##                        Race.fctrBlack 
##                           0.499911437 
##             Race.fctrPacific Islander 
##                           0.027777413 
##                    Region.fctrMidwest 
##                           0.034678764 
##                  Region.fctrNortheast 
##                           0.151019068 
##                       Region.fctrWest 
##                           0.091052386 
##                          Sex.fctrMale 
##                           0.229847065 
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
##  [1] ""                                     
##  [2] ".rnorm"                               
##  [3] "Age"                                  
##  [4] "Citizenship.fctrCitizen, Naturalized" 
##  [5] "Citizenship.fctrNon-Citizen"          
##  [6] "Education.fctrBachelor's degree"      
##  [7] "Education.fctrDoctorate degree"       
##  [8] "Education.fctrHigh school"            
##  [9] "Education.fctrMaster's degree"        
## [10] "Education.fctrNA.my"                  
## [11] "Education.fctrNo high school diploma" 
## [12] "Education.fctrProfessional degree"    
## [13] "Education.fctrSome college, no degree"
## [14] "Hispanic"                             
## [15] "Married.fctrMarried"                  
## [16] "Married.fctrNA.my"                    
## [17] "Married.fctrNever Married"            
## [18] "Married.fctrSeparated"                
## [19] "Married.fctrWidowed"                  
## [20] "PeopleInHousehold"                    
## [21] "Race.fctrAmerican Indian"             
## [22] "Race.fctrAsian"                       
## [23] "Race.fctrBlack"                       
## [24] "Race.fctrMultiracial"                 
## [25] "Race.fctrPacific Islander"            
## [26] "Region.fctrMidwest"                   
## [27] "Region.fctrNortheast"                 
## [28] "Region.fctrWest"                      
## [29] "Sex.fctrMale"
## [1] TRUE
# From here to save(), this should all be in one function
#   these are executed in the same seq twice more:
#       fit.data.training & predict.data.new chunks
print(sprintf("%s fit prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet fit prediction diagnostics:"
glbObsFit <- glb_get_predictions(df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 rsp_var = glb_rsp_var)
print(sprintf("%s OOB prediction diagnostics:", glb_sel_mdl_id))
## [1] "All.X##rcv#glmnet OOB prediction diagnostics:"
glbObsOOB <- glb_get_predictions(df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
                                     rsp_var = glb_rsp_var)

print(glb_featsimp_df <- myget_feats_importance(mdl = glb_sel_mdl, featsimp_df = NULL))
##                                       All.X..rcv.glmnet.imp.Disabled
## .rnorm                                                     1.5250461
## Age                                                        4.9502539
## Citizenship.fctrCitizen, Naturalized                      47.4802548
## Citizenship.fctrNon-Citizen                               80.8187616
## Education.fctrBachelor's degree                           59.1559838
## Education.fctrDoctorate degree                            58.8506019
## Education.fctrHigh school                                 34.0699104
## Education.fctrMaster's degree                             81.6105115
## Education.fctrNA.my                                        0.0000000
## Education.fctrNo high school diploma                     100.0000000
## Education.fctrProfessional degree                         71.1360427
## Education.fctrSome college, no degree                     10.8622226
## Hispanic                                                   0.0000000
## Married.fctrMarried                                       80.5845919
## Married.fctrNA.my                                          0.0000000
## Married.fctrNever Married                                  0.0000000
## Married.fctrSeparated                                     15.0539265
## Married.fctrWidowed                                        0.0000000
## PeopleInHousehold                                          1.5572023
## Race.fctrAmerican Indian                                   0.8471631
## Race.fctrAsian                                             6.8442014
## Race.fctrBlack                                            29.1551897
## Race.fctrMultiracial                                       8.6753643
## Race.fctrPacific Islander                                 25.8652446
## Region.fctrMidwest                                         6.7340630
## Region.fctrNortheast                                       1.5329980
## Region.fctrWest                                            9.8859677
## Sex.fctrMale                                               0.0000000
##                                       All.X..rcv.glmnet.imp.Employed
## .rnorm                                                      1.061148
## Age                                                         0.000000
## Citizenship.fctrCitizen, Naturalized                        7.787895
## Citizenship.fctrNon-Citizen                                 7.227984
## Education.fctrBachelor's degree                            14.350902
## Education.fctrDoctorate degree                             72.186222
## Education.fctrHigh school                                  42.836408
## Education.fctrMaster's degree                              24.226282
## Education.fctrNA.my                                         0.000000
## Education.fctrNo high school diploma                       80.094677
## Education.fctrProfessional degree                          50.306390
## Education.fctrSome college, no degree                      20.401790
## Hispanic                                                    5.086637
## Married.fctrMarried                                         0.000000
## Married.fctrNA.my                                           0.000000
## Married.fctrNever Married                                  19.383808
## Married.fctrSeparated                                       0.000000
## Married.fctrWidowed                                        11.058165
## PeopleInHousehold                                           0.000000
## Race.fctrAmerican Indian                                   34.669462
## Race.fctrAsian                                              0.000000
## Race.fctrBlack                                             19.032460
## Race.fctrMultiracial                                       12.038783
## Race.fctrPacific Islander                                  15.024038
## Region.fctrMidwest                                         13.781795
## Region.fctrNortheast                                        8.249320
## Region.fctrWest                                             0.000000
## Sex.fctrMale                                               20.843611
##                                       All.X..rcv.glmnet.imp.Not.in.Labor.Force
## .rnorm                                                                0.000000
## Age                                                                   3.879180
## Citizenship.fctrCitizen, Naturalized                                  3.886102
## Citizenship.fctrNon-Citizen                                          14.922307
## Education.fctrBachelor's degree                                       0.000000
## Education.fctrDoctorate degree                                        0.000000
## Education.fctrHigh school                                             0.000000
## Education.fctrMaster's degree                                         3.826702
## Education.fctrNA.my                                                   0.000000
## Education.fctrNo high school diploma                                 90.911477
## Education.fctrProfessional degree                                     0.000000
## Education.fctrSome college, no degree                                21.607572
## Hispanic                                                              9.740632
## Married.fctrMarried                                                  24.377008
## Married.fctrNA.my                                                     0.000000
## Married.fctrNever Married                                            31.347716
## Married.fctrSeparated                                                 3.525010
## Married.fctrWidowed                                                  54.767522
## PeopleInHousehold                                                    13.790449
## Race.fctrAmerican Indian                                              0.000000
## Race.fctrAsian                                                       41.270984
## Race.fctrBlack                                                        8.553671
## Race.fctrMultiracial                                                  5.097845
## Race.fctrPacific Islander                                             0.000000
## Region.fctrMidwest                                                   14.084344
## Region.fctrNortheast                                                  0.000000
## Region.fctrWest                                                       0.000000
## Sex.fctrMale                                                         67.291846
##                                       All.X..rcv.glmnet.imp.Retired
## .rnorm                                                    1.5581039
## Age                                                      16.9487180
## Citizenship.fctrCitizen, Naturalized                     19.7809372
## Citizenship.fctrNon-Citizen                              27.3778456
## Education.fctrBachelor's degree                           3.8671767
## Education.fctrDoctorate degree                            3.2717620
## Education.fctrHigh school                                 7.1433732
## Education.fctrMaster's degree                            22.1583093
## Education.fctrNA.my                                       0.0000000
## Education.fctrNo high school diploma                      0.0000000
## Education.fctrProfessional degree                         0.0000000
## Education.fctrSome college, no degree                     0.0000000
## Hispanic                                                  0.0000000
## Married.fctrMarried                                      38.3635891
## Married.fctrNA.my                                         0.0000000
## Married.fctrNever Married                                 4.6328211
## Married.fctrSeparated                                    20.2361192
## Married.fctrWidowed                                      49.5531148
## PeopleInHousehold                                        14.9510504
## Race.fctrAmerican Indian                                 16.9468444
## Race.fctrAsian                                           14.0094019
## Race.fctrBlack                                            0.0000000
## Race.fctrMultiracial                                     10.5548579
## Race.fctrPacific Islander                                17.3463875
## Region.fctrMidwest                                        0.0000000
## Region.fctrNortheast                                      0.1003404
## Region.fctrWest                                           7.5367906
## Sex.fctrMale                                             10.5284526
##                                       All.X..rcv.glmnet.imp.Unemployed imp
## .rnorm                                                       0.0000000  -1
## Age                                                          0.3375848  -2
## Citizenship.fctrCitizen, Naturalized                         0.0000000  -3
## Citizenship.fctrNon-Citizen                                  0.0000000  -4
## Education.fctrBachelor's degree                              0.0000000  -5
## Education.fctrDoctorate degree                               0.0000000  -6
## Education.fctrHigh school                                    0.5911445  -7
## Education.fctrMaster's degree                                0.0000000  -8
## Education.fctrNA.my                                          0.0000000  -9
## Education.fctrNo high school diploma                        11.0521930 -10
## Education.fctrProfessional degree                            0.0000000 -11
## Education.fctrSome college, no degree                        0.3188346 -12
## Hispanic                                                    16.0729143 -13
## Married.fctrMarried                                         50.7011130 -14
## Married.fctrNA.my                                            0.0000000 -15
## Married.fctrNever Married                                    2.4655739 -16
## Married.fctrSeparated                                        5.3005399 -17
## Married.fctrWidowed                                         10.6888708 -18
## PeopleInHousehold                                            6.7356407 -19
## Race.fctrAmerican Indian                                    21.2926566 -20
## Race.fctrAsian                                               5.1886845 -21
## Race.fctrBlack                                              46.9542665 -22
## Race.fctrMultiracial                                         0.0000000 -23
## Race.fctrPacific Islander                                    2.6089982 -24
## Region.fctrMidwest                                           3.2572087 -25
## Region.fctrNortheast                                        14.1844916 -26
## Region.fctrWest                                              8.5521108 -27
## Sex.fctrMale                                                21.5884246 -28
#mdl_id <-"RFE.X.glmnet"; glb_featsimp_df <- myget_feats_importance(glb_models_lst[[mdl_id]], glb_featsimp_df); glb_featsimp_df[, paste0(mdl_id, ".imp")] <- glb_featsimp_df$imp; print(glb_featsimp_df)
#print(head(sbst_featsimp_df <- subset(glb_featsimp_df, is.na(RFE.X.glmnet.imp) | (abs(RFE.X.YeoJohnson.glmnet.imp - RFE.X.glmnet.imp) > 0.0001), select=-imp)))
#print(orderBy(~ -cor.y.abs, subset(glb_feats_df, id %in% c(row.names(sbst_featsimp_df), "startprice.dcm1.is9", "D.weight.post.stop.sum"))))

# Used again in fit.data.training & predict.data.new chunks
glb_analytics_diag_plots <- function(obs_df, mdl_id, prob_threshold=NULL) {
    if (!is.null(featsimp_df <- glb_featsimp_df)) {
        featsimp_df$feat <- gsub("`(.*?)`", "\\1", row.names(featsimp_df))    
        featsimp_df$feat.interact <- gsub("(.*?):(.*)", "\\2", featsimp_df$feat)
        featsimp_df$feat <- gsub("(.*?):(.*)", "\\1", featsimp_df$feat)    
        featsimp_df$feat.interact <- 
            ifelse(featsimp_df$feat.interact == featsimp_df$feat, 
                                            NA, featsimp_df$feat.interact)
        featsimp_df$feat <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat)
        featsimp_df$feat.interact <- 
            gsub("(.*?)\\.fctr(.*)", "\\1\\.fctr", featsimp_df$feat.interact) 
        featsimp_df <- orderBy(~ -imp.max, 
            summaryBy(imp ~ feat + feat.interact, data=featsimp_df,
                      FUN=max))    
        #rex_str=":(.*)"; txt_vctr=tail(featsimp_df$feat); ret_lst <- regexec(rex_str, txt_vctr); ret_lst <- regmatches(txt_vctr, ret_lst); ret_vctr <- sapply(1:length(ret_lst), function(pos_ix) ifelse(length(ret_lst[[pos_ix]]) > 0, ret_lst[[pos_ix]], "")); print(ret_vctr <- ret_vctr[ret_vctr != ""])    
        
        featsimp_df <- subset(featsimp_df, !is.na(imp.max))
        if (nrow(featsimp_df) > 5) {
            warning("Limiting important feature scatter plots to 5 out of ",
                    nrow(featsimp_df))
            featsimp_df <- head(featsimp_df, 5)
        }
        
    #     if (!all(is.na(featsimp_df$feat.interact)))
    #         stop("not implemented yet")
        rsp_var_out <- mygetPredictIds(glb_rsp_var, mdl_id)$value
        for (var in featsimp_df$feat) {
            plot_df <- melt(obs_df, id.vars = var, 
                            measure.vars = c(glb_rsp_var, rsp_var_out))
    
            print(myplot_scatter(plot_df, var, "value", colorcol_name = "variable",
                                facet_colcol_name = "variable", jitter = TRUE) + 
                          guides(color = FALSE))
        }
    }
    
    if (glb_is_regression) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No important features in glb_fin_mdl") else
            print(myplot_prediction_regression(df=obs_df, 
                        feat_x=ifelse(nrow(featsimp_df) > 1, featsimp_df$feat[2],
                                      ".rownames"), 
                                               feat_y=featsimp_df$feat[1],
                        rsp_var=glb_rsp_var, rsp_var_out=rsp_var_out,
                        id_vars=glbFeatsId)
    #               + facet_wrap(reformulate(featsimp_df$feat[2])) # if [1 or 2] is a factor
    #               + geom_point(aes_string(color="<col_name>.fctr")) #  to color the plot
                  )
    }    
    
    if (glb_is_classification) {
        if (is.null(featsimp_df) || (nrow(featsimp_df) == 0))
            warning("No features in selected model are statistically important")
        else print(myplot_prediction_classification(df = obs_df, 
                                feat_x = ifelse(nrow(featsimp_df) > 1, 
                                                featsimp_df$feat[2], ".rownames"),
                                               feat_y = featsimp_df$feat[1],
                                                rsp_var = glb_rsp_var, 
                                                rsp_var_out = rsp_var_out, 
                                                id_vars = glbFeatsId,
                                                prob_threshold = prob_threshold))
    }    
}

if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id, 
            prob_threshold = glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                           "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id)                  
## Warning in glb_analytics_diag_plots(obs_df = glbObsOOB, mdl_id =
## glb_sel_mdl_id): Limiting important feature scatter plots to 5 out of 10

## [1] "Min/Max Boundaries: "
##    .rownames EmploymentStatus.fctr EmploymentStatus.fctr.All.X..rcv.glmnet
## 1      82324              Employed                                Employed
## 2      61899              Disabled                                 Retired
## 3       5444              Disabled                                 Retired
## 4      67205              Disabled                                 Retired
## 5      11233              Disabled                                 Retired
## 6     116110              Disabled                                 Retired
## 7     123652    Not.in.Labor.Force                                 Retired
## 8      55065              Disabled                                 Retired
## 9      72295              Disabled                      Not.in.Labor.Force
## 10     57730              Disabled                      Not.in.Labor.Force
## 11     57728              Disabled                      Not.in.Labor.Force
## 12     32062              Disabled                                Employed
## 13     29898              Disabled                      Not.in.Labor.Force
## 14     11138              Disabled                      Not.in.Labor.Force
##    EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 1                                     0.7778538
## 2                                     0.9556859
## 3                                     0.9503372
## 4                                     0.9470713
## 5                                     0.9432245
## 6                                     0.8885648
## 7                                     0.8851479
## 8                                     0.8369017
## 9                                     0.7046648
## 10                                    0.7007226
## 11                                    0.7001114
## 12                                    0.6627180
## 13                                    0.5393194
## 14                                    0.5362889
##    EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 1                                        FALSE
## 2                                         TRUE
## 3                                         TRUE
## 4                                         TRUE
## 5                                         TRUE
## 6                                         TRUE
## 7                                         TRUE
## 8                                         TRUE
## 9                                         TRUE
## 10                                        TRUE
## 11                                        TRUE
## 12                                        TRUE
## 13                                        TRUE
## 14                                        TRUE
##    EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 1                                      0.000000000
## 2                                      0.013422721
## 3                                      0.040495037
## 4                                      0.043283137
## 5                                      0.025951125
## 6                                      0.094001537
## 7                                      0.008501801
## 8                                      0.139822440
## 9                                      0.019134060
## 10                                     0.024769281
## 11                                     0.024868089
## 12                                     0.019493680
## 13                                     0.039002030
## 14                                     0.039547328
##    EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 1                                            TRUE
## 2                                           FALSE
## 3                                           FALSE
## 4                                           FALSE
## 5                                           FALSE
## 6                                           FALSE
## 7                                           FALSE
## 8                                           FALSE
## 9                                           FALSE
## 10                                          FALSE
## 11                                          FALSE
## 12                                          FALSE
## 13                                          FALSE
## 14                                          FALSE
##    EmploymentStatus.fctr.All.X..rcv.glmnet.accurate
## 1                                              TRUE
## 2                                             FALSE
## 3                                             FALSE
## 4                                             FALSE
## 5                                             FALSE
## 6                                             FALSE
## 7                                             FALSE
## 8                                             FALSE
## 9                                             FALSE
## 10                                            FALSE
## 11                                            FALSE
## 12                                            FALSE
## 13                                            FALSE
## 14                                            FALSE
##    EmploymentStatus.fctr.All.X..rcv.glmnet.error .label
## 1                                     0.00000000  82324
## 2                                     0.04431409  61899
## 3                                     0.04966279   5444
## 4                                     0.05292870  67205
## 5                                     0.05677555  11233
## 6                                     0.11143520 116110
## 7                                     0.11485210 123652
## 8                                     0.16309828  55065
## 9                                     0.29533517  72295
## 10                                    0.29927742  57730
## 11                                    0.29988859  57728
## 12                                    0.33728198  32062
## 13                                    0.46068055  29898
## 14                                    0.46371111  11138
## [1] "Inaccurate: "
##   .rownames EmploymentStatus.fctr EmploymentStatus.fctr.All.X..rcv.glmnet
## 1     30168              Employed                                 Retired
## 2     74437              Disabled                                 Retired
## 3     26711              Employed                                 Retired
## 4     65338              Employed                                 Retired
## 5     18966              Employed                                 Retired
## 6     35251              Employed                                 Retired
##   EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 1                                    0.9717483
## 2                                    0.9710020
## 3                                    0.9704153
## 4                                    0.9686106
## 5                                    0.9683116
## 6                                    0.9681395
##   EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 1                                        TRUE
## 2                                        TRUE
## 3                                        TRUE
## 4                                        TRUE
## 5                                        TRUE
## 6                                        TRUE
##   EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 1                                      0.01580123
## 2                                      0.01416346
## 3                                      0.01279953
## 4                                      0.02308573
## 5                                      0.01119513
## 6                                      0.01574859
##   EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 1                                          FALSE
## 2                                          FALSE
## 3                                          FALSE
## 4                                          FALSE
## 5                                          FALSE
## 6                                          FALSE
##   EmploymentStatus.fctr.All.X..rcv.glmnet.accurate
## 1                                            FALSE
## 2                                            FALSE
## 3                                            FALSE
## 4                                            FALSE
## 5                                            FALSE
## 6                                            FALSE
##   EmploymentStatus.fctr.All.X..rcv.glmnet.error
## 1                                    0.02825168
## 2                                    0.02899799
## 3                                    0.02958467
## 4                                    0.03138936
## 5                                    0.03168842
## 6                                    0.03186054
##      .rownames EmploymentStatus.fctr
## 1072     98956    Not.in.Labor.Force
## 1321     15491    Not.in.Labor.Force
## 3129     41018               Retired
## 3657     82571    Not.in.Labor.Force
## 3930      4221    Not.in.Labor.Force
## 6261     17235               Retired
##      EmploymentStatus.fctr.All.X..rcv.glmnet
## 1072                                Employed
## 1321                                Employed
## 3129                                Employed
## 3657                                Employed
## 3930                                Employed
## 6261                                Employed
##      EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 1072                                    0.8049305
## 1321                                    0.7875132
## 3129                                    0.6858792
## 3657                                    0.6579430
## 3930                                    0.6435715
## 6261                                    0.5049103
##      EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 1072                                        TRUE
## 1321                                        TRUE
## 3129                                        TRUE
## 3657                                        TRUE
## 3930                                        TRUE
## 6261                                        TRUE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 1072                                       0.1642977
## 1321                                       0.1623444
## 3129                                       0.2503397
## 3657                                       0.2875168
## 3930                                       0.2147354
## 6261                                       0.4440958
##      EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 1072                                          FALSE
## 1321                                          FALSE
## 3129                                          FALSE
## 3657                                          FALSE
## 3930                                          FALSE
## 6261                                          FALSE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.accurate
## 1072                                            FALSE
## 1321                                            FALSE
## 3129                                            FALSE
## 3657                                            FALSE
## 3930                                            FALSE
## 6261                                            FALSE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.error
## 1072                                     0.1950695
## 1321                                     0.2124868
## 3129                                     0.3141208
## 3657                                     0.3420570
## 3930                                     0.3564285
## 6261                                     0.4950897
##      .rownames EmploymentStatus.fctr
## 7856     82366              Disabled
## 7857     31285            Unemployed
## 7858    103225              Employed
## 7859     86883              Disabled
## 7860     77820    Not.in.Labor.Force
## 7861      7506               Retired
##      EmploymentStatus.fctr.All.X..rcv.glmnet
## 7856                      Not.in.Labor.Force
## 7857                                Disabled
## 7858                      Not.in.Labor.Force
## 7859                                Employed
## 7860                                 Retired
## 7861                                Employed
##      EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 7856                                    0.3120301
## 7857                                    0.3111775
## 7858                                    0.3077395
## 7859                                    0.3036536
## 7860                                    0.2755269
## 7861                                    0.2743326
##      EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 7856                                        TRUE
## 7857                                        TRUE
## 7858                                        TRUE
## 7859                                        TRUE
## 7860                                        TRUE
## 7861                                        TRUE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 7856                                      0.30214635
## 7857                                      0.05596686
## 7858                                      0.29883522
## 7859                                      0.29630243
## 7860                                      0.18757496
## 7861                                      0.24790773
##      EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 7856                                          FALSE
## 7857                                          FALSE
## 7858                                          FALSE
## 7859                                          FALSE
## 7860                                          FALSE
## 7861                                          FALSE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.accurate
## 7856                                            FALSE
## 7857                                            FALSE
## 7858                                            FALSE
## 7859                                            FALSE
## 7860                                            FALSE
## 7861                                            FALSE
##      EmploymentStatus.fctr.All.X..rcv.glmnet.error
## 7856                                     0.6879699
## 7857                                     0.6888225
## 7858                                     0.6922605
## 7859                                     0.6963464
## 7860                                     0.7244731
## 7861                                     0.7256674

if (!is.null(glbFeatsCategory)) {
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsFit, mdl_id = glb_sel_mdl_id, 
                                 label = "fit"), 
                            by = glbFeatsCategory, all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    glbLvlCategory <- merge(glbLvlCategory, 
            myget_category_stats(obs_df = glbObsOOB, mdl_id = glb_sel_mdl_id,
                                 label="OOB"),
                          #by=glbFeatsCategory, all=TRUE) glb_ctgry-df already contains .n.OOB ?
                          all = TRUE)
    row.names(glbLvlCategory) <- glbLvlCategory[, glbFeatsCategory]
    if (any(grepl("OOB", glbMdlMetricsEval)))
        print(orderBy(~-err.abs.OOB.mean, glbLvlCategory)) else
            print(orderBy(~-err.abs.fit.mean, glbLvlCategory))
    print(colSums(glbLvlCategory[, -grep(glbFeatsCategory, names(glbLvlCategory))]))
}
##        .category .n.OOB .n.Fit .n.Tst .freqRatio.Fit .freqRatio.OOB
## .dummy    .dummy  28370  77143  25789              1              1
##        .freqRatio.Tst err.abs.fit.sum err.abs.fit.mean .n.fit
## .dummy              1        3967.069       0.05142488  77143
##        err.abs.OOB.sum err.abs.OOB.mean
## .dummy        1481.543       0.05222217
##           .n.OOB           .n.Fit           .n.Tst   .freqRatio.Fit 
##     2.837000e+04     7.714300e+04     2.578900e+04     1.000000e+00 
##   .freqRatio.OOB   .freqRatio.Tst  err.abs.fit.sum err.abs.fit.mean 
##     1.000000e+00     1.000000e+00     3.967069e+03     5.142488e-02 
##           .n.fit  err.abs.OOB.sum err.abs.OOB.mean 
##     7.714300e+04     1.481543e+03     5.222217e-02
write.csv(glbObsOOB[, c(glbFeatsId, 
                grep(glb_rsp_var, names(glbObsOOB), fixed=TRUE, value=TRUE))], 
    paste0(gsub(".", "_", paste0(glbOut$pfx, glb_sel_mdl_id), fixed=TRUE), 
           "_OOBobs.csv"), row.names=FALSE)

fit.models_2_chunk_df <- 
    myadd_chunk(NULL, "fit.models_2_bgn", label.minor = "teardown")
##              label step_major step_minor label_minor      bgn end elapsed
## 1 fit.models_2_bgn          1          0    teardown 1310.711  NA      NA
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.models", major.inc=FALSE)
##         label step_major step_minor label_minor      bgn      end elapsed
## 18 fit.models          8          2           2 1278.196 1310.739  32.544
## 19 fit.models          8          3           3 1310.740       NA      NA
# if (sum(is.na(glbObsAll$D.P.http)) > 0)
#         stop("fit.models_3: Why is this happening ?")

#stop(here"); glb2Sav()
sync_glb_obs_df <- function() {
    # Merge or cbind ?
    for (col in setdiff(names(glbObsFit), names(glbObsTrn)))
        glbObsTrn[glbObsTrn$.lcn == "Fit", col] <<- glbObsFit[, col]
    for (col in setdiff(names(glbObsFit), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "Fit", col] <<- glbObsFit[, col]
    if (all(is.na(glbObsNew[, glb_rsp_var])))
        for (col in setdiff(names(glbObsOOB), names(glbObsTrn)))
            glbObsTrn[glbObsTrn$.lcn == "OOB", col] <<- glbObsOOB[, col]
    for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
        glbObsAll[glbObsAll$.lcn == "OOB", col] <<- glbObsOOB[, col]
}
sync_glb_obs_df()
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
replay.petrisim(pn = glb_analytics_pn, 
    replay.trans = (glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "model.selected")), flip_coord = TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0

glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc = TRUE)
##                label step_major step_minor label_minor      bgn      end
## 19        fit.models          8          3           3 1310.740 1331.742
## 20 fit.data.training          9          0           0 1331.743       NA
##    elapsed
## 19  21.002
## 20      NA

Step 9.0: fit data training

#load(paste0(glb_inp_pfx, "dsk.RData"))

if (!is.null(glb_fin_mdl_id) && (glb_fin_mdl_id %in% names(glb_models_lst))) {
    warning("Final model same as user selected model")
    glb_fin_mdl <- glb_models_lst[[glb_fin_mdl_id]]
} else 
# if (nrow(glbObsFit) + length(glbObsFitOutliers) == nrow(glbObsTrn))
if (!all(is.na(glbObsNew[, glb_rsp_var])))
{    
    warning("Final model same as glb_sel_mdl_id")
    glb_fin_mdl_id <- paste0("Final.", glb_sel_mdl_id)
    glb_fin_mdl <- glb_sel_mdl
    glb_models_lst[[glb_fin_mdl_id]] <- glb_fin_mdl
    mdlDf <- glb_models_df[glb_models_df$id == glb_sel_mdl_id, ]
    mdlDf$id <- glb_fin_mdl_id
    glb_models_df <- rbind(glb_models_df, mdlDf)
} else {    
            if (grepl("RFE\\.X", names(glbMdlFamilies))) {
                indepVar <- mygetIndepVar(glb_feats_df)
                rfe_trn_results <- 
                    myrun_rfe(glbObsTrn, indepVar, glbRFESizes[["Final"]])
                if (!isTRUE(all.equal(sort(predictors(rfe_trn_results)),
                                      sort(predictors(rfe_fit_results))))) {
                    print("Diffs predictors(rfe_trn_results) vs. predictors(rfe_fit_results):")
                    print(setdiff(predictors(rfe_trn_results), predictors(rfe_fit_results)))
                    print("Diffs predictors(rfe_fit_results) vs. predictors(rfe_trn_results):")
                    print(setdiff(predictors(rfe_fit_results), predictors(rfe_trn_results)))
            }
        }
    # }    

    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        # Fit selected models on glbObsTrn
        for (mdl_id in gsub(".prob", "", 
gsub(mygetPredictIds(glb_rsp_var)$value, "", row.names(mdlimp_df), fixed = TRUE),
                            fixed = TRUE)) {
            mdl_id_components <- unlist(strsplit(mdl_id, "[.]"))
            mdlIdPfx <- paste0(c(head(mdl_id_components, -1), "Train"), 
                               collapse = ".")
            if (grepl("RFE\\.X\\.", mdlIdPfx)) 
                mdlIndepVars <- myadjustInteractionFeats(glb_feats_df, myextract_actual_feats(
                    predictors(rfe_trn_results))) else
                mdlIndepVars <- trim(unlist(
            strsplit(glb_models_df[glb_models_df$id == mdl_id, "feats"], "[,]")))
            ret_lst <- 
                myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                        id.prefix = mdlIdPfx, 
                        type = glb_model_type, tune.df = glbMdlTuneParams,
                        trainControl.method = "repeatedcv",
                        trainControl.number = glb_rcv_n_folds,
                        trainControl.repeats = glb_rcv_n_repeats,
                        trainControl.classProbs = glb_is_classification,
                        trainControl.summaryFunction = glbMdlMetricSummaryFn,
                        train.metric = glbMdlMetricSummary, 
                        train.maximize = glbMdlMetricMaximize,    
                        train.method = tail(mdl_id_components, 1))),
                    indepVar = mdlIndepVars,
                    rsp_var = glb_rsp_var, 
                    fit_df = glbObsTrn, OOB_df = NULL)
            
            glbObsTrn <- glb_get_predictions(df = glbObsTrn,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
            glbObsNew <- glb_get_predictions(df = glbObsNew,
                                                mdl_id = tail(glb_models_df$id, 1), 
                                                rsp_var = glb_rsp_var,
                                                prob_threshold_def = 
                    subset(glb_models_df, id == mdl_id)$opt.prob.threshold.OOB)
        }    
    }
    
    # "Final" model
    if ((model_method <- glb_sel_mdl$method) == "custom")
        # get actual method from the mdl_id
        model_method <- tail(unlist(strsplit(glb_sel_mdl_id, "[.]")), 1)
        
    if (grepl("Ensemble", glb_sel_mdl_id)) {
        # Find which models are relevant
        mdlimp_df <- subset(myget_feats_importance(glb_sel_mdl), imp > 5)
        if (glb_is_classification && glb_is_binomial)
            indepVar <- gsub("(.*)\\.(.*)\\.prob", "\\1\\.Train\\.\\2\\.prob",
                                    row.names(mdlimp_df)) else
            indepVar <- gsub("(.*)\\.(.*)", "\\1\\.Train\\.\\2",
                                    row.names(mdlimp_df))
    } else 
    if (grepl("RFE.X", glb_sel_mdl_id, fixed = TRUE)) {
        indepVar <- myextract_actual_feats(predictors(rfe_trn_results))
    } else indepVar <- 
                trim(unlist(strsplit(glb_models_df[glb_models_df$id ==
                                                   glb_sel_mdl_id
                                                   , "feats"], "[,]")))
        
    if (!is.null(glb_preproc_methods) &&
        ((match_pos <- regexpr(gsub(".", "\\.", 
                                    paste(glb_preproc_methods, collapse = "|"),
                                   fixed = TRUE), glb_sel_mdl_id)) != -1))
        ths_preProcess <- str_sub(glb_sel_mdl_id, match_pos, 
                                match_pos + attr(match_pos, "match.length") - 1) else
        ths_preProcess <- NULL                                      

    mdl_id_pfx <- ifelse(grepl("Ensemble", glb_sel_mdl_id),
                                   "Final.Ensemble", "Final")
    
    trnobs_df <- glbObsTrn 
    if (!is.null(glbObsTrnOutliers[[mdl_id_pfx]])) {
        trnobs_df <- glbObsTrn[!(glbObsTrn[, glbFeatsId] %in% glbObsTrnOutliers[[mdl_id_pfx]]), ]
        print(sprintf("Outliers removed: %d", nrow(glbObsTrn) - nrow(trnobs_df)))
        print(setdiff(glbObsTrn[, glbFeatsId], trnobs_df[, glbFeatsId]))
    }    
        
    # Force fitting of Final.glm to identify outliers
    method_vctr <- unique(c(myparseMdlId(glb_sel_mdl_id)$alg, glbMdlFamilies[["Final"]]))
    for (method in method_vctr) {
        #source("caret_nominalTrainWorkflow.R")
        
        # glmnet requires at least 2 indep vars
        if ((length(indepVar) == 1) && (method %in% "glmnet"))
            next
        
        ret_lst <- 
            myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst = list(
                    id.prefix = mdl_id_pfx, 
                    type = glb_model_type, trainControl.method = "repeatedcv",
                    trainControl.number = glb_rcv_n_folds, 
                    trainControl.repeats = glb_rcv_n_repeats,
                    trainControl.classProbs = glb_is_classification,
                    trainControl.summaryFunction = glbMdlMetricSummaryFn,
                    trainControl.allowParallel = glbMdlAllowParallel,
                    train.metric = glbMdlMetricSummary, 
                    train.maximize = glbMdlMetricMaximize,    
                    train.method = method,
                    train.preProcess = ths_preProcess)),
                indepVar = indepVar, rsp_var = glb_rsp_var, 
                fit_df = trnobs_df, OOB_df = NULL)
        
        if ((length(method_vctr) == 1) || (method != "glm")) {
            glb_fin_mdl <- glb_models_lst[[length(glb_models_lst)]] 
            glb_fin_mdl_id <- glb_models_df[length(glb_models_lst), "id"]
        }
    }
        
}
## [1] "myfit_mdl: enter: 0.000000 secs"
## [1] "fitting model: Final##rcv#glmnet"
## [1] "    indepVar: Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold"
## [1] "myfit_mdl: setup complete: 0.738000 secs"
## + Fold1.Rep1: alpha=0.100, lambda=0.1013 
## - Fold1.Rep1: alpha=0.100, lambda=0.1013 
## + Fold1.Rep1: alpha=0.325, lambda=0.1013 
## - Fold1.Rep1: alpha=0.325, lambda=0.1013 
## + Fold1.Rep1: alpha=0.550, lambda=0.1013 
## - Fold1.Rep1: alpha=0.550, lambda=0.1013 
## + Fold1.Rep1: alpha=0.775, lambda=0.1013 
## - Fold1.Rep1: alpha=0.775, lambda=0.1013 
## + Fold1.Rep1: alpha=1.000, lambda=0.1013 
## - Fold1.Rep1: alpha=1.000, lambda=0.1013 
## + Fold2.Rep1: alpha=0.100, lambda=0.1013 
## - Fold2.Rep1: alpha=0.100, lambda=0.1013 
## + Fold2.Rep1: alpha=0.325, lambda=0.1013 
## - Fold2.Rep1: alpha=0.325, lambda=0.1013 
## + Fold2.Rep1: alpha=0.550, lambda=0.1013 
## - Fold2.Rep1: alpha=0.550, lambda=0.1013 
## + Fold2.Rep1: alpha=0.775, lambda=0.1013 
## - Fold2.Rep1: alpha=0.775, lambda=0.1013 
## + Fold2.Rep1: alpha=1.000, lambda=0.1013 
## - Fold2.Rep1: alpha=1.000, lambda=0.1013 
## + Fold3.Rep1: alpha=0.100, lambda=0.1013 
## - Fold3.Rep1: alpha=0.100, lambda=0.1013 
## + Fold3.Rep1: alpha=0.325, lambda=0.1013 
## - Fold3.Rep1: alpha=0.325, lambda=0.1013 
## + Fold3.Rep1: alpha=0.550, lambda=0.1013 
## - Fold3.Rep1: alpha=0.550, lambda=0.1013 
## + Fold3.Rep1: alpha=0.775, lambda=0.1013 
## - Fold3.Rep1: alpha=0.775, lambda=0.1013 
## + Fold3.Rep1: alpha=1.000, lambda=0.1013 
## - Fold3.Rep1: alpha=1.000, lambda=0.1013 
## + Fold1.Rep2: alpha=0.100, lambda=0.1013 
## - Fold1.Rep2: alpha=0.100, lambda=0.1013 
## + Fold1.Rep2: alpha=0.325, lambda=0.1013 
## - Fold1.Rep2: alpha=0.325, lambda=0.1013 
## + Fold1.Rep2: alpha=0.550, lambda=0.1013 
## - Fold1.Rep2: alpha=0.550, lambda=0.1013 
## + Fold1.Rep2: alpha=0.775, lambda=0.1013 
## - Fold1.Rep2: alpha=0.775, lambda=0.1013 
## + Fold1.Rep2: alpha=1.000, lambda=0.1013 
## - Fold1.Rep2: alpha=1.000, lambda=0.1013 
## + Fold2.Rep2: alpha=0.100, lambda=0.1013 
## - Fold2.Rep2: alpha=0.100, lambda=0.1013 
## + Fold2.Rep2: alpha=0.325, lambda=0.1013 
## - Fold2.Rep2: alpha=0.325, lambda=0.1013 
## + Fold2.Rep2: alpha=0.550, lambda=0.1013 
## - Fold2.Rep2: alpha=0.550, lambda=0.1013 
## + Fold2.Rep2: alpha=0.775, lambda=0.1013 
## - Fold2.Rep2: alpha=0.775, lambda=0.1013 
## + Fold2.Rep2: alpha=1.000, lambda=0.1013 
## - Fold2.Rep2: alpha=1.000, lambda=0.1013 
## + Fold3.Rep2: alpha=0.100, lambda=0.1013 
## - Fold3.Rep2: alpha=0.100, lambda=0.1013 
## + Fold3.Rep2: alpha=0.325, lambda=0.1013 
## - Fold3.Rep2: alpha=0.325, lambda=0.1013 
## + Fold3.Rep2: alpha=0.550, lambda=0.1013 
## - Fold3.Rep2: alpha=0.550, lambda=0.1013 
## + Fold3.Rep2: alpha=0.775, lambda=0.1013 
## - Fold3.Rep2: alpha=0.775, lambda=0.1013 
## + Fold3.Rep2: alpha=1.000, lambda=0.1013 
## - Fold3.Rep2: alpha=1.000, lambda=0.1013 
## + Fold1.Rep3: alpha=0.100, lambda=0.1013 
## - Fold1.Rep3: alpha=0.100, lambda=0.1013 
## + Fold1.Rep3: alpha=0.325, lambda=0.1013 
## - Fold1.Rep3: alpha=0.325, lambda=0.1013 
## + Fold1.Rep3: alpha=0.550, lambda=0.1013 
## - Fold1.Rep3: alpha=0.550, lambda=0.1013 
## + Fold1.Rep3: alpha=0.775, lambda=0.1013 
## - Fold1.Rep3: alpha=0.775, lambda=0.1013 
## + Fold1.Rep3: alpha=1.000, lambda=0.1013 
## - Fold1.Rep3: alpha=1.000, lambda=0.1013 
## + Fold2.Rep3: alpha=0.100, lambda=0.1013 
## - Fold2.Rep3: alpha=0.100, lambda=0.1013 
## + Fold2.Rep3: alpha=0.325, lambda=0.1013 
## - Fold2.Rep3: alpha=0.325, lambda=0.1013 
## + Fold2.Rep3: alpha=0.550, lambda=0.1013 
## - Fold2.Rep3: alpha=0.550, lambda=0.1013 
## + Fold2.Rep3: alpha=0.775, lambda=0.1013 
## - Fold2.Rep3: alpha=0.775, lambda=0.1013 
## + Fold2.Rep3: alpha=1.000, lambda=0.1013 
## - Fold2.Rep3: alpha=1.000, lambda=0.1013 
## + Fold3.Rep3: alpha=0.100, lambda=0.1013 
## - Fold3.Rep3: alpha=0.100, lambda=0.1013 
## + Fold3.Rep3: alpha=0.325, lambda=0.1013 
## - Fold3.Rep3: alpha=0.325, lambda=0.1013 
## + Fold3.Rep3: alpha=0.550, lambda=0.1013 
## - Fold3.Rep3: alpha=0.550, lambda=0.1013 
## + Fold3.Rep3: alpha=0.775, lambda=0.1013 
## - Fold3.Rep3: alpha=0.775, lambda=0.1013 
## + Fold3.Rep3: alpha=1.000, lambda=0.1013 
## - Fold3.Rep3: alpha=1.000, lambda=0.1013 
## Aggregating results
## Selecting tuning parameters
## Fitting alpha = 1, lambda = 0.000218 on full training set
## [1] "myfit_mdl: train complete: 1637.374000 secs"
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: alpha
## Warning in myfit_mdl(mdl_specs_lst = myinit_mdl_specs_lst(mdl_specs_lst
## = list(id.prefix = mdl_id_pfx, : model's bestTune found at an extreme of
## tuneGrid for parameter: lambda

##             Length Class      Mode     
## a0          370    -none-     numeric  
## beta          5    -none-     list     
## dfmat       370    -none-     numeric  
## df           74    -none-     numeric  
## dim           2    -none-     numeric  
## lambda       74    -none-     numeric  
## dev.ratio    74    -none-     numeric  
## nulldev       1    -none-     numeric  
## npasses       1    -none-     numeric  
## jerr          1    -none-     numeric  
## offset        1    -none-     logical  
## classnames    5    -none-     character
## grouped       1    -none-     logical  
## call          5    -none-     call     
## nobs          1    -none-     numeric  
## lambdaOpt     1    -none-     numeric  
## xNames       28    -none-     character
## problemType   1    -none-     character
## tuneValue     2    data.frame list     
## obsLevels     5    -none-     character
## [1] "min lambda > lambdaOpt:"
## [1] "class: Disabled:"
##                                       
##                           -0.63888122 
##                                   Age 
##                            0.05231109 
##  Citizenship.fctrCitizen, Naturalized 
##                           -0.49033684 
##           Citizenship.fctrNon-Citizen 
##                           -0.85384229 
##       Education.fctrBachelor's degree 
##                           -0.67620626 
##        Education.fctrDoctorate degree 
##                           -0.58200084 
##             Education.fctrHigh school 
##                            0.35014528 
##         Education.fctrMaster's degree 
##                           -0.84578839 
##  Education.fctrNo high school diploma 
##                            1.05787757 
##     Education.fctrProfessional degree 
##                           -0.83105312 
## Education.fctrSome college, no degree 
##                            0.04352802 
##                   Married.fctrMarried 
##                           -0.85948490 
##                 Married.fctrSeparated 
##                            0.21805484 
##                     PeopleInHousehold 
##                           -0.02475525 
##              Race.fctrAmerican Indian 
##                            0.06003993 
##                        Race.fctrAsian 
##                           -0.05776675 
##                        Race.fctrBlack 
##                            0.34753090 
##                  Race.fctrMultiracial 
##                            0.06472791 
##             Race.fctrPacific Islander 
##                            0.17134900 
##                    Region.fctrMidwest 
##                           -0.07553574 
##                  Region.fctrNortheast 
##                           -0.03254712 
##                       Region.fctrWest 
##                           -0.11142301 
## [1] "class: Employed:"
##                                       
##                           4.037424167 
##                                .rnorm 
##                           0.005725224 
##  Citizenship.fctrCitizen, Naturalized 
##                           0.072911872 
##           Citizenship.fctrNon-Citizen 
##                           0.106329047 
##       Education.fctrBachelor's degree 
##                           0.150025880 
##        Education.fctrDoctorate degree 
##                           0.737594465 
##             Education.fctrHigh school 
##                          -0.432415002 
##         Education.fctrMaster's degree 
##                           0.299525848 
##  Education.fctrNo high school diploma 
##                          -0.821219124 
##     Education.fctrProfessional degree 
##                           0.587187423 
## Education.fctrSome college, no degree 
##                          -0.204319003 
##                              Hispanic 
##                           0.066151756 
##             Married.fctrNever Married 
##                          -0.198578021 
##                   Married.fctrWidowed 
##                          -0.046795531 
##              Race.fctrAmerican Indian 
##                          -0.304628331 
##                        Race.fctrBlack 
##                          -0.163732768 
##                  Race.fctrMultiracial 
##                          -0.202447200 
##             Race.fctrPacific Islander 
##                          -0.062622824 
##                    Region.fctrMidwest 
##                           0.158275969 
##                  Region.fctrNortheast 
##                           0.060652531 
##                       Region.fctrWest 
##                          -0.022935468 
##                          Sex.fctrMale 
##                           0.214773719 
## [1] "class: Not.in.Labor.Force:"
##                                       
##                            3.20010813 
##                                   Age 
##                           -0.04104332 
##           Citizenship.fctrNon-Citizen 
##                            0.16845202 
##             Education.fctrHigh school 
##                            0.00659570 
##         Education.fctrMaster's degree 
##                           -0.03622108 
##  Education.fctrNo high school diploma 
##                            0.97788073 
## Education.fctrSome college, no degree 
##                            0.25406019 
##                              Hispanic 
##                           -0.09148494 
##                   Married.fctrMarried 
##                            0.24292446 
##             Married.fctrNever Married 
##                            0.32482603 
##                 Married.fctrSeparated 
##                           -0.02523701 
##                   Married.fctrWidowed 
##                            0.66714724 
##                     PeopleInHousehold 
##                            0.15067149 
##                        Race.fctrAsian 
##                            0.44167139 
##                        Race.fctrBlack 
##                           -0.04575543 
##                    Region.fctrMidwest 
##                           -0.10758757 
##                          Sex.fctrMale 
##                           -0.73270833 
## [1] "class: Retired:"
##                                                                    .rnorm 
##                          -7.79769527                          -0.02223912 
##                                  Age Citizenship.fctrCitizen, Naturalized 
##                           0.18109988                          -0.21892704 
##          Citizenship.fctrNon-Citizen      Education.fctrBachelor's degree 
##                          -0.28632489                           0.08222431 
##            Education.fctrHigh school        Education.fctrMaster's degree 
##                          -0.06603050                           0.26445231 
##                  Married.fctrMarried            Married.fctrNever Married 
##                           0.36846243                          -0.07385050 
##                Married.fctrSeparated                  Married.fctrWidowed 
##                          -0.14254986                           0.53991113 
##                    PeopleInHousehold             Race.fctrAmerican Indian 
##                          -0.16091689                          -0.03108225 
##                       Race.fctrAsian                 Race.fctrMultiracial 
##                           0.13693219                          -0.14565247 
##            Race.fctrPacific Islander                 Region.fctrNortheast 
##                          -0.01435219                          -0.06200164 
##                      Region.fctrWest                         Sex.fctrMale 
##                           0.04968121                          -0.10215077 
## [1] "class: Unemployed:"
##                                                                       Age 
##                          1.199044190                         -0.005001215 
## Education.fctrNo high school diploma                             Hispanic 
##                         -0.089470493                          0.138530924 
##                  Married.fctrMarried            Married.fctrNever Married 
##                         -0.566750536                          0.005308366 
##                  Married.fctrWidowed                    PeopleInHousehold 
##                         -0.055625871                          0.074743995 
##             Race.fctrAmerican Indian                       Race.fctrBlack 
##                          0.372819157                          0.528513290 
##                 Race.fctrMultiracial            Race.fctrPacific Islander 
##                          0.092689898                          0.077943957 
##                   Region.fctrMidwest                 Region.fctrNortheast 
##                          0.045924146                          0.154696199 
##                      Region.fctrWest                         Sex.fctrMale 
##                          0.075284939                          0.169018182 
## [1] "max lambda < lambdaOpt:"
## [1] "Feats mismatch between coefs_left & rght:"
##  [1] ""                                     
##  [2] ".rnorm"                               
##  [3] "Age"                                  
##  [4] "Citizenship.fctrCitizen, Naturalized" 
##  [5] "Citizenship.fctrNon-Citizen"          
##  [6] "Education.fctrBachelor's degree"      
##  [7] "Education.fctrDoctorate degree"       
##  [8] "Education.fctrHigh school"            
##  [9] "Education.fctrMaster's degree"        
## [10] "Education.fctrNA.my"                  
## [11] "Education.fctrNo high school diploma" 
## [12] "Education.fctrProfessional degree"    
## [13] "Education.fctrSome college, no degree"
## [14] "Hispanic"                             
## [15] "Married.fctrMarried"                  
## [16] "Married.fctrNA.my"                    
## [17] "Married.fctrNever Married"            
## [18] "Married.fctrSeparated"                
## [19] "Married.fctrWidowed"                  
## [20] "PeopleInHousehold"                    
## [21] "Race.fctrAmerican Indian"             
## [22] "Race.fctrAsian"                       
## [23] "Race.fctrBlack"                       
## [24] "Race.fctrMultiracial"                 
## [25] "Race.fctrPacific Islander"            
## [26] "Region.fctrMidwest"                   
## [27] "Region.fctrNortheast"                 
## [28] "Region.fctrWest"                      
## [29] "Sex.fctrMale"                         
## [1] "myfit_mdl: train diagnostics complete: 1638.228000 secs"
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                281     4356                268     807
##   Employed                151    56382               2238    2962
##   Not.in.Labor.Force       52     8959               5844     391
##   Retired                 110     4603                 26   13880
##   Unemployed               19     3527                511     146
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##       Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
##      0.7239582      0.4747524      0.7212500      0.7266541      0.5850748 
## AccuracyPValue  McnemarPValue 
##      0.0000000      0.0000000 
## [1] "myfit_mdl: predict complete: 1640.102000 secs"
##                  id
## 1 Final##rcv#glmnet
##                                                                                                               feats
## 1 Age,Married.fctr,Education.fctr,Region.fctr,Race.fctr,.rnorm,Citizenship.fctr,Hispanic,Sex.fctr,PeopleInHousehold
##   max.nTuningRuns min.elapsedtime.everything min.elapsedtime.final
## 1              25                   1636.356                  44.8
##   max.Accuracy.fit max.AccuracyLower.fit max.AccuracyUpper.fit
## 1         0.723895               0.72125             0.7266541
##   max.Kappa.fit max.AccuracySD.fit max.KappaSD.fit
## 1     0.4745565        0.001551918     0.002809817
## [1] "myfit_mdl: exit: 1640.112000 secs"
rm(ret_lst)
glb_chunks_df <- myadd_chunk(glb_chunks_df, "fit.data.training", major.inc=FALSE)
##                label step_major step_minor label_minor      bgn      end
## 20 fit.data.training          9          0           0 1331.743 2972.311
## 21 fit.data.training          9          1           1 2972.312       NA
##     elapsed
## 20 1640.568
## 21       NA
#stop(here"); glb2Sav()
if (glb_is_classification && glb_is_binomial) 
    prob_threshold <- glb_models_df[glb_models_df$id == glb_sel_mdl_id,
                                        "opt.prob.threshold.OOB"] else 
    prob_threshold <- NULL

if (grepl("Ensemble", glb_fin_mdl_id)) {
    # Get predictions for each model in ensemble; Outliers that have been moved to OOB might not have been predicted yet
    mdlEnsembleComps <- unlist(str_split(subset(glb_models_df, 
                                                id == glb_fin_mdl_id)$feats, ","))
    if (glb_is_classification && glb_is_binomial)
        mdlEnsembleComps <- gsub("\\.prob$", "", mdlEnsembleComps)
    mdlEnsembleComps <- gsub(paste0("^", 
                        gsub(".", "\\.", mygetPredictIds(glb_rsp_var)$value, fixed = TRUE)),
                             "", mdlEnsembleComps)
    for (mdl_id in mdlEnsembleComps) {
        glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
        glbObsNew <- glb_get_predictions(df = glbObsNew, mdl_id = mdl_id, 
                                            rsp_var = glb_rsp_var,
                                            prob_threshold_def = prob_threshold)
    }    
}
glbObsTrn <- glb_get_predictions(df = glbObsTrn, mdl_id = glb_fin_mdl_id, 
                                     rsp_var = glb_rsp_var,
                                    prob_threshold_def = prob_threshold)

glb_featsimp_df <- myget_feats_importance(mdl=glb_fin_mdl,
                                          featsimp_df=glb_featsimp_df)
#glb_featsimp_df[, paste0(glb_fin_mdl_id, ".imp")] <- glb_featsimp_df$imp
print(glb_featsimp_df)
##                                       All.X..rcv.glmnet.imp.Disabled
## .rnorm                                                     1.5250461
## Age                                                        4.9502539
## Citizenship.fctrCitizen, Naturalized                      47.4802548
## Citizenship.fctrNon-Citizen                               80.8187616
## Education.fctrBachelor's degree                           59.1559838
## Education.fctrDoctorate degree                            58.8506019
## Education.fctrHigh school                                 34.0699104
## Education.fctrMaster's degree                             81.6105115
## Education.fctrNA.my                                        0.0000000
## Education.fctrNo high school diploma                     100.0000000
## Education.fctrProfessional degree                         71.1360427
## Education.fctrSome college, no degree                     10.8622226
## Hispanic                                                   0.0000000
## Married.fctrMarried                                       80.5845919
## Married.fctrNA.my                                          0.0000000
## Married.fctrNever Married                                  0.0000000
## Married.fctrSeparated                                     15.0539265
## Married.fctrWidowed                                        0.0000000
## PeopleInHousehold                                          1.5572023
## Race.fctrAmerican Indian                                   0.8471631
## Race.fctrAsian                                             6.8442014
## Race.fctrBlack                                            29.1551897
## Race.fctrMultiracial                                       8.6753643
## Race.fctrPacific Islander                                 25.8652446
## Region.fctrMidwest                                         6.7340630
## Region.fctrNortheast                                       1.5329980
## Region.fctrWest                                            9.8859677
## Sex.fctrMale                                               0.0000000
##                                       All.X..rcv.glmnet.imp.Employed
## .rnorm                                                      1.061148
## Age                                                         0.000000
## Citizenship.fctrCitizen, Naturalized                        7.787895
## Citizenship.fctrNon-Citizen                                 7.227984
## Education.fctrBachelor's degree                            14.350902
## Education.fctrDoctorate degree                             72.186222
## Education.fctrHigh school                                  42.836408
## Education.fctrMaster's degree                              24.226282
## Education.fctrNA.my                                         0.000000
## Education.fctrNo high school diploma                       80.094677
## Education.fctrProfessional degree                          50.306390
## Education.fctrSome college, no degree                      20.401790
## Hispanic                                                    5.086637
## Married.fctrMarried                                         0.000000
## Married.fctrNA.my                                           0.000000
## Married.fctrNever Married                                  19.383808
## Married.fctrSeparated                                       0.000000
## Married.fctrWidowed                                        11.058165
## PeopleInHousehold                                           0.000000
## Race.fctrAmerican Indian                                   34.669462
## Race.fctrAsian                                              0.000000
## Race.fctrBlack                                             19.032460
## Race.fctrMultiracial                                       12.038783
## Race.fctrPacific Islander                                  15.024038
## Region.fctrMidwest                                         13.781795
## Region.fctrNortheast                                        8.249320
## Region.fctrWest                                             0.000000
## Sex.fctrMale                                               20.843611
##                                       All.X..rcv.glmnet.imp.Not.in.Labor.Force
## .rnorm                                                                0.000000
## Age                                                                   3.879180
## Citizenship.fctrCitizen, Naturalized                                  3.886102
## Citizenship.fctrNon-Citizen                                          14.922307
## Education.fctrBachelor's degree                                       0.000000
## Education.fctrDoctorate degree                                        0.000000
## Education.fctrHigh school                                             0.000000
## Education.fctrMaster's degree                                         3.826702
## Education.fctrNA.my                                                   0.000000
## Education.fctrNo high school diploma                                 90.911477
## Education.fctrProfessional degree                                     0.000000
## Education.fctrSome college, no degree                                21.607572
## Hispanic                                                              9.740632
## Married.fctrMarried                                                  24.377008
## Married.fctrNA.my                                                     0.000000
## Married.fctrNever Married                                            31.347716
## Married.fctrSeparated                                                 3.525010
## Married.fctrWidowed                                                  54.767522
## PeopleInHousehold                                                    13.790449
## Race.fctrAmerican Indian                                              0.000000
## Race.fctrAsian                                                       41.270984
## Race.fctrBlack                                                        8.553671
## Race.fctrMultiracial                                                  5.097845
## Race.fctrPacific Islander                                             0.000000
## Region.fctrMidwest                                                   14.084344
## Region.fctrNortheast                                                  0.000000
## Region.fctrWest                                                       0.000000
## Sex.fctrMale                                                         67.291846
##                                       All.X..rcv.glmnet.imp.Retired
## .rnorm                                                    1.5581039
## Age                                                      16.9487180
## Citizenship.fctrCitizen, Naturalized                     19.7809372
## Citizenship.fctrNon-Citizen                              27.3778456
## Education.fctrBachelor's degree                           3.8671767
## Education.fctrDoctorate degree                            3.2717620
## Education.fctrHigh school                                 7.1433732
## Education.fctrMaster's degree                            22.1583093
## Education.fctrNA.my                                       0.0000000
## Education.fctrNo high school diploma                      0.0000000
## Education.fctrProfessional degree                         0.0000000
## Education.fctrSome college, no degree                     0.0000000
## Hispanic                                                  0.0000000
## Married.fctrMarried                                      38.3635891
## Married.fctrNA.my                                         0.0000000
## Married.fctrNever Married                                 4.6328211
## Married.fctrSeparated                                    20.2361192
## Married.fctrWidowed                                      49.5531148
## PeopleInHousehold                                        14.9510504
## Race.fctrAmerican Indian                                 16.9468444
## Race.fctrAsian                                           14.0094019
## Race.fctrBlack                                            0.0000000
## Race.fctrMultiracial                                     10.5548579
## Race.fctrPacific Islander                                17.3463875
## Region.fctrMidwest                                        0.0000000
## Region.fctrNortheast                                      0.1003404
## Region.fctrWest                                           7.5367906
## Sex.fctrMale                                             10.5284526
##                                       All.X..rcv.glmnet.imp.Unemployed
## .rnorm                                                       0.0000000
## Age                                                          0.3375848
## Citizenship.fctrCitizen, Naturalized                         0.0000000
## Citizenship.fctrNon-Citizen                                  0.0000000
## Education.fctrBachelor's degree                              0.0000000
## Education.fctrDoctorate degree                               0.0000000
## Education.fctrHigh school                                    0.5911445
## Education.fctrMaster's degree                                0.0000000
## Education.fctrNA.my                                          0.0000000
## Education.fctrNo high school diploma                        11.0521930
## Education.fctrProfessional degree                            0.0000000
## Education.fctrSome college, no degree                        0.3188346
## Hispanic                                                    16.0729143
## Married.fctrMarried                                         50.7011130
## Married.fctrNA.my                                            0.0000000
## Married.fctrNever Married                                    2.4655739
## Married.fctrSeparated                                        5.3005399
## Married.fctrWidowed                                         10.6888708
## PeopleInHousehold                                            6.7356407
## Race.fctrAmerican Indian                                    21.2926566
## Race.fctrAsian                                               5.1886845
## Race.fctrBlack                                              46.9542665
## Race.fctrMultiracial                                         0.0000000
## Race.fctrPacific Islander                                    2.6089982
## Region.fctrMidwest                                           3.2572087
## Region.fctrNortheast                                        14.1844916
## Region.fctrWest                                              8.5521108
## Sex.fctrMale                                                21.5884246
##                                       Final..rcv.glmnet.imp.Disabled
## .rnorm                                                      0.000000
## Age                                                         4.944910
## Citizenship.fctrCitizen, Naturalized                       46.351000
## Citizenship.fctrNon-Citizen                                80.712770
## Education.fctrBachelor's degree                            63.921032
## Education.fctrDoctorate degree                             55.015897
## Education.fctrHigh school                                  33.098847
## Education.fctrMaster's degree                              79.951444
## Education.fctrNA.my                                         0.000000
## Education.fctrNo high school diploma                      100.000000
## Education.fctrProfessional degree                          78.558535
## Education.fctrSome college, no degree                       4.114656
## Hispanic                                                    0.000000
## Married.fctrMarried                                        81.246159
## Married.fctrNA.my                                           0.000000
## Married.fctrNever Married                                   0.000000
## Married.fctrSeparated                                      20.612483
## Married.fctrWidowed                                         0.000000
## PeopleInHousehold                                           2.340087
## Race.fctrAmerican Indian                                    5.675508
## Race.fctrAsian                                              5.460627
## Race.fctrBlack                                             32.851713
## Race.fctrMultiracial                                        6.118658
## Race.fctrPacific Islander                                  16.197432
## Region.fctrMidwest                                          7.140310
## Region.fctrNortheast                                        3.076644
## Region.fctrWest                                            10.532694
## Sex.fctrMale                                                0.000000
##                                       Final..rcv.glmnet.imp.Employed
## .rnorm                                                     0.5411991
## Age                                                        0.0000000
## Citizenship.fctrCitizen, Naturalized                       6.8922788
## Citizenship.fctrNon-Citizen                               10.0511675
## Education.fctrBachelor's degree                           14.1817810
## Education.fctrDoctorate degree                            69.7239913
## Education.fctrHigh school                                 40.8757133
## Education.fctrMaster's degree                             28.3138481
## Education.fctrNA.my                                        0.0000000
## Education.fctrNo high school diploma                      77.6289381
## Education.fctrProfessional degree                         55.5061795
## Education.fctrSome college, no degree                     19.3140500
## Hispanic                                                   6.2532525
## Married.fctrMarried                                        0.0000000
## Married.fctrNA.my                                          0.0000000
## Married.fctrNever Married                                 18.7713613
## Married.fctrSeparated                                      0.0000000
## Married.fctrWidowed                                        4.4235299
## PeopleInHousehold                                          0.0000000
## Race.fctrAmerican Indian                                  28.7961802
## Race.fctrAsian                                             0.0000000
## Race.fctrBlack                                            15.4774780
## Race.fctrMultiracial                                      19.1371106
## Race.fctrPacific Islander                                  5.9196665
## Region.fctrMidwest                                        14.9616528
## Region.fctrNortheast                                       5.7334168
## Region.fctrWest                                            2.1680645
## Sex.fctrMale                                              20.3023228
##                                       Final..rcv.glmnet.imp.Not.in.Labor.Force
## .rnorm                                                               0.0000000
## Age                                                                  3.8797797
## Citizenship.fctrCitizen, Naturalized                                 0.0000000
## Citizenship.fctrNon-Citizen                                         15.9235833
## Education.fctrBachelor's degree                                      0.0000000
## Education.fctrDoctorate degree                                       0.0000000
## Education.fctrHigh school                                            0.6234842
## Education.fctrMaster's degree                                        3.4239386
## Education.fctrNA.my                                                  0.0000000
## Education.fctrNo high school diploma                                92.4379866
## Education.fctrProfessional degree                                    0.0000000
## Education.fctrSome college, no degree                               24.0160296
## Hispanic                                                             8.6479709
## Married.fctrMarried                                                 22.9633810
## Married.fctrNA.my                                                    0.0000000
## Married.fctrNever Married                                           30.7054464
## Married.fctrSeparated                                                2.3856269
## Married.fctrWidowed                                                 63.0646928
## PeopleInHousehold                                                   14.2428100
## Race.fctrAmerican Indian                                             0.0000000
## Race.fctrAsian                                                      41.7507091
## Race.fctrBlack                                                       4.3252103
## Race.fctrMultiracial                                                 0.0000000
## Race.fctrPacific Islander                                            0.0000000
## Region.fctrMidwest                                                  10.1701343
## Region.fctrNortheast                                                 0.0000000
## Region.fctrWest                                                      0.0000000
## Sex.fctrMale                                                        69.2621101
##                                       Final..rcv.glmnet.imp.Retired
## .rnorm                                                     2.102239
## Age                                                       17.119172
## Citizenship.fctrCitizen, Naturalized                      20.694932
## Citizenship.fctrNon-Citizen                               27.065976
## Education.fctrBachelor's degree                            7.772573
## Education.fctrDoctorate degree                             0.000000
## Education.fctrHigh school                                  6.241790
## Education.fctrMaster's degree                             24.998385
## Education.fctrNA.my                                        0.000000
## Education.fctrNo high school diploma                       0.000000
## Education.fctrProfessional degree                          0.000000
## Education.fctrSome college, no degree                      0.000000
## Hispanic                                                   0.000000
## Married.fctrMarried                                       34.830347
## Married.fctrNA.my                                          0.000000
## Married.fctrNever Married                                  6.981007
## Married.fctrSeparated                                     13.475081
## Married.fctrWidowed                                       51.037204
## PeopleInHousehold                                         15.211297
## Race.fctrAmerican Indian                                   2.938171
## Race.fctrAsian                                            12.944049
## Race.fctrBlack                                             0.000000
## Race.fctrMultiracial                                      13.768367
## Race.fctrPacific Islander                                  1.356697
## Region.fctrMidwest                                         0.000000
## Region.fctrNortheast                                       5.860947
## Region.fctrWest                                            4.696310
## Sex.fctrMale                                               9.656200
##                                       Final..rcv.glmnet.imp.Unemployed imp
## .rnorm                                                       0.0000000  -1
## Age                                                          0.4727594  -2
## Citizenship.fctrCitizen, Naturalized                         0.0000000  -3
## Citizenship.fctrNon-Citizen                                  0.0000000  -4
## Education.fctrBachelor's degree                              0.0000000  -5
## Education.fctrDoctorate degree                               0.0000000  -6
## Education.fctrHigh school                                    0.0000000  -7
## Education.fctrMaster's degree                                0.0000000  -8
## Education.fctrNA.my                                          0.0000000  -9
## Education.fctrNo high school diploma                         8.4575470 -10
## Education.fctrProfessional degree                            0.0000000 -11
## Education.fctrSome college, no degree                        0.0000000 -12
## Hispanic                                                    13.0951755 -13
## Married.fctrMarried                                         53.5743032 -14
## Married.fctrNA.my                                            0.0000000 -15
## Married.fctrNever Married                                    0.5017940 -16
## Married.fctrSeparated                                        0.0000000 -17
## Married.fctrWidowed                                          5.2582522 -18
## PeopleInHousehold                                            7.0654674 -19
## Race.fctrAmerican Indian                                    35.2421838 -20
## Race.fctrAsian                                               0.0000000 -21
## Race.fctrBlack                                              49.9597784 -22
## Race.fctrMultiracial                                         8.7618738 -23
## Race.fctrPacific Islander                                    7.3679563 -24
## Region.fctrMidwest                                           4.3411589 -25
## Region.fctrNortheast                                        14.6232611 -26
## Region.fctrWest                                              7.1166022 -27
## Sex.fctrMale                                                15.9771023 -28
if (glb_is_classification && glb_is_binomial)
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id, 
            prob_threshold=glb_models_df[glb_models_df$id == glb_sel_mdl_id, 
                                         "opt.prob.threshold.OOB"]) else
    glb_analytics_diag_plots(obs_df=glbObsTrn, mdl_id=glb_fin_mdl_id)                  
## Warning in glb_analytics_diag_plots(obs_df = glbObsTrn, mdl_id =
## glb_fin_mdl_id): Limiting important feature scatter plots to 5 out of 10

## [1] "Min/Max Boundaries: "
##    .rownames EmploymentStatus.fctr EmploymentStatus.fctr.All.X..rcv.glmnet
## 1      92232               Retired                                 Retired
## 2      91473    Not.in.Labor.Force                                    <NA>
## 3      82324              Employed                                    <NA>
## 4      80194              Disabled                                 Retired
## 5      55388              Disabled                                 Retired
## 6      73495              Disabled                                 Retired
## 7      57377    Not.in.Labor.Force                                 Retired
## 8     111997              Disabled                                 Retired
## 9     123652    Not.in.Labor.Force                                    <NA>
## 10     55065              Disabled                                    <NA>
## 11     33583              Disabled                      Not.in.Labor.Force
## 12     34152    Not.in.Labor.Force                                Employed
## 13     34149              Disabled                      Not.in.Labor.Force
## 14     57503              Employed                      Not.in.Labor.Force
## 15     55993    Not.in.Labor.Force                                Employed
## 16    114440    Not.in.Labor.Force                                Employed
##    EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 1                                     0.9466763
## 2                                            NA
## 3                                            NA
## 4                                     0.9641804
## 5                                     0.9616346
## 6                                     0.9610895
## 7                                     0.9574020
## 8                                     0.9331917
## 9                                            NA
## 10                                           NA
## 11                                    0.7670838
## 12                                    0.7179204
## 13                                    0.5753285
## 14                                    0.5475758
## 15                                    0.4783561
## 16                                    0.4410888
##    EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 1                                        FALSE
## 2                                           NA
## 3                                           NA
## 4                                         TRUE
## 5                                         TRUE
## 6                                         TRUE
## 7                                         TRUE
## 8                                         TRUE
## 9                                           NA
## 10                                          NA
## 11                                        TRUE
## 12                                        TRUE
## 13                                        TRUE
## 14                                        TRUE
## 15                                        TRUE
## 16                                        TRUE
##    EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 1                                      0.000000000
## 2                                               NA
## 3                                               NA
## 4                                      0.015755430
## 5                                      0.024267880
## 6                                      0.023343962
## 7                                      0.000793178
## 8                                      0.052234638
## 9                                               NA
## 10                                              NA
## 11                                     0.023841333
## 12                                     0.172575843
## 13                                     0.038986105
## 14                                     0.351226657
## 15                                     0.392210213
## 16                                     0.433120978
##    EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 1                                            TRUE
## 2                                              NA
## 3                                              NA
## 4                                           FALSE
## 5                                           FALSE
## 6                                           FALSE
## 7                                           FALSE
## 8                                           FALSE
## 9                                              NA
## 10                                             NA
## 11                                          FALSE
## 12                                          FALSE
## 13                                          FALSE
## 14                                          FALSE
## 15                                          FALSE
## 16                                          FALSE
##    EmploymentStatus.fctr.Final..rcv.glmnet
## 1                                  Retired
## 2                       Not.in.Labor.Force
## 3                                 Employed
## 4                                  Retired
## 5                                  Retired
## 6                                  Retired
## 7                                  Retired
## 8                                  Retired
## 9                                  Retired
## 10                                 Retired
## 11                      Not.in.Labor.Force
## 12                                Employed
## 13                      Not.in.Labor.Force
## 14                      Not.in.Labor.Force
## 15                                Employed
## 16                                Employed
##    EmploymentStatus.fctr.Final..rcv.glmnet.prob
## 1                                     0.9486844
## 2                                     0.6513522
## 3                                     0.7776858
## 4                                     0.9654976
## 5                                     0.9630189
## 6                                     0.9618780
## 7                                     0.9586793
## 8                                     0.9349725
## 9                                     0.8837644
## 10                                    0.8360837
## 11                                    0.7622472
## 12                                    0.7207351
## 13                                    0.5656594
## 14                                    0.5330480
## 15                                    0.4785182
## 16                                    0.4436580
##    EmploymentStatus.fctr.Final..rcv.glmnet.err
## 1                                        FALSE
## 2                                        FALSE
## 3                                        FALSE
## 4                                         TRUE
## 5                                         TRUE
## 6                                         TRUE
## 7                                         TRUE
## 8                                         TRUE
## 9                                         TRUE
## 10                                        TRUE
## 11                                        TRUE
## 12                                        TRUE
## 13                                        TRUE
## 14                                        TRUE
## 15                                        TRUE
## 16                                        TRUE
##    EmploymentStatus.fctr.Final..rcv.glmnet.err.abs
## 1                                     0.0000000000
## 2                                     0.0000000000
## 3                                     0.0000000000
## 4                                     0.0143991713
## 5                                     0.0226915610
## 6                                     0.0221760536
## 7                                     0.0008187548
## 8                                     0.0501773379
## 9                                     0.0089483302
## 10                                    0.1403765993
## 11                                    0.0237390119
## 12                                    0.1696334648
## 13                                    0.0398646937
## 14                                    0.3614746510
## 15                                    0.3939317654
## 16                                    0.4318972297
##    EmploymentStatus.fctr.Final..rcv.glmnet.is.acc
## 1                                            TRUE
## 2                                            TRUE
## 3                                            TRUE
## 4                                           FALSE
## 5                                           FALSE
## 6                                           FALSE
## 7                                           FALSE
## 8                                           FALSE
## 9                                           FALSE
## 10                                          FALSE
## 11                                          FALSE
## 12                                          FALSE
## 13                                          FALSE
## 14                                          FALSE
## 15                                          FALSE
## 16                                          FALSE
##    EmploymentStatus.fctr.Final..rcv.glmnet.accurate
## 1                                              TRUE
## 2                                              TRUE
## 3                                              TRUE
## 4                                             FALSE
## 5                                             FALSE
## 6                                             FALSE
## 7                                             FALSE
## 8                                             FALSE
## 9                                             FALSE
## 10                                            FALSE
## 11                                            FALSE
## 12                                            FALSE
## 13                                            FALSE
## 14                                            FALSE
## 15                                            FALSE
## 16                                            FALSE
##    EmploymentStatus.fctr.Final..rcv.glmnet.error .label
## 1                                     0.00000000  92232
## 2                                     0.00000000  91473
## 3                                     0.00000000  82324
## 4                                     0.03450237  80194
## 5                                     0.03698107  55388
## 6                                     0.03812201  73495
## 7                                     0.04132066  57377
## 8                                     0.06502753 111997
## 9                                     0.11623560 123652
## 10                                    0.16391630  55065
## 11                                    0.23775277  33583
## 12                                    0.27926488  34152
## 13                                    0.43434061  34149
## 14                                    0.46695196  57503
## 15                                    0.52148185  55993
## 16                                    0.55634204 114440
## [1] "Inaccurate: "
##   .rownames EmploymentStatus.fctr EmploymentStatus.fctr.All.X..rcv.glmnet
## 1     73130              Disabled                                 Retired
## 2     35230    Not.in.Labor.Force                                 Retired
## 3     66446              Disabled                                 Retired
## 4     30168              Employed                                    <NA>
## 5     74437              Disabled                                    <NA>
## 6     11251              Disabled                                 Retired
##   EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 1                                    0.9736238
## 2                                    0.9726779
## 3                                    0.9702989
## 4                                           NA
## 5                                           NA
## 6                                    0.9709380
##   EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 1                                        TRUE
## 2                                        TRUE
## 3                                        TRUE
## 4                                          NA
## 5                                          NA
## 6                                        TRUE
##   EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 1                                    0.0064589096
## 2                                    0.0007402925
## 3                                    0.0079048628
## 4                                              NA
## 5                                              NA
## 6                                    0.0141980346
##   EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 1                                          FALSE
## 2                                          FALSE
## 3                                          FALSE
## 4                                             NA
## 5                                             NA
## 6                                          FALSE
##   EmploymentStatus.fctr.Final..rcv.glmnet
## 1                                 Retired
## 2                                 Retired
## 3                                 Retired
## 4                                 Retired
## 5                                 Retired
## 6                                 Retired
##   EmploymentStatus.fctr.Final..rcv.glmnet.prob
## 1                                    0.9748694
## 2                                    0.9723952
## 3                                    0.9721108
## 4                                    0.9719574
## 5                                    0.9717480
## 6                                    0.9716955
##   EmploymentStatus.fctr.Final..rcv.glmnet.err
## 1                                        TRUE
## 2                                        TRUE
## 3                                        TRUE
## 4                                        TRUE
## 5                                        TRUE
## 6                                        TRUE
##   EmploymentStatus.fctr.Final..rcv.glmnet.err.abs
## 1                                     0.005875948
## 2                                     0.000796662
## 3                                     0.006977207
## 4                                     0.015728671
## 5                                     0.013072004
## 6                                     0.013093493
##   EmploymentStatus.fctr.Final..rcv.glmnet.is.acc
## 1                                          FALSE
## 2                                          FALSE
## 3                                          FALSE
## 4                                          FALSE
## 5                                          FALSE
## 6                                          FALSE
##   EmploymentStatus.fctr.Final..rcv.glmnet.accurate
## 1                                            FALSE
## 2                                            FALSE
## 3                                            FALSE
## 4                                            FALSE
## 5                                            FALSE
## 6                                            FALSE
##   EmploymentStatus.fctr.Final..rcv.glmnet.error
## 1                                    0.02513063
## 2                                    0.02760484
## 3                                    0.02788922
## 4                                    0.02804258
## 5                                    0.02825205
## 6                                    0.02830450
##       .rownames EmploymentStatus.fctr
## 6758      18549            Unemployed
## 8674      61193              Disabled
## 15670    101660               Retired
## 16697       262    Not.in.Labor.Force
## 18772       488              Disabled
## 22453     77741              Disabled
##       EmploymentStatus.fctr.All.X..rcv.glmnet
## 6758                                 Employed
## 8674                                 Employed
## 15670                                Employed
## 16697                                Employed
## 18772                                    <NA>
## 22453                                Employed
##       EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 6758                                     0.7504163
## 8674                                     0.7287896
## 15670                                    0.6220756
## 16697                                    0.6078959
## 18772                                           NA
## 22453                                    0.5189605
##       EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 6758                                         TRUE
## 8674                                         TRUE
## 15670                                        TRUE
## 16697                                        TRUE
## 18772                                          NA
## 22453                                        TRUE
##       EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 6758                                       0.08135210
## 8674                                       0.02325500
## 15670                                      0.19227345
## 16697                                      0.08180032
## 18772                                              NA
## 22453                                      0.01402917
##       EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 6758                                           FALSE
## 8674                                           FALSE
## 15670                                          FALSE
## 16697                                          FALSE
## 18772                                             NA
## 22453                                          FALSE
##       EmploymentStatus.fctr.Final..rcv.glmnet
## 6758                                 Employed
## 8674                                 Employed
## 15670                                Employed
## 16697                                Employed
## 18772                                Employed
## 22453                                Employed
##       EmploymentStatus.fctr.Final..rcv.glmnet.prob
## 6758                                     0.7536517
## 8674                                     0.7253134
## 15670                                    0.6266511
## 16697                                    0.6108497
## 18772                                    0.5766080
## 22453                                    0.5181191
##       EmploymentStatus.fctr.Final..rcv.glmnet.err
## 6758                                         TRUE
## 8674                                         TRUE
## 15670                                        TRUE
## 16697                                        TRUE
## 18772                                        TRUE
## 22453                                        TRUE
##       EmploymentStatus.fctr.Final..rcv.glmnet.err.abs
## 6758                                       0.07596810
## 8674                                       0.02438197
## 15670                                      0.18444870
## 16697                                      0.08000917
## 18772                                      0.10111372
## 22453                                      0.01415913
##       EmploymentStatus.fctr.Final..rcv.glmnet.is.acc
## 6758                                           FALSE
## 8674                                           FALSE
## 15670                                          FALSE
## 16697                                          FALSE
## 18772                                          FALSE
## 22453                                          FALSE
##       EmploymentStatus.fctr.Final..rcv.glmnet.accurate
## 6758                                             FALSE
## 8674                                             FALSE
## 15670                                            FALSE
## 16697                                            FALSE
## 18772                                            FALSE
## 22453                                            FALSE
##       EmploymentStatus.fctr.Final..rcv.glmnet.error
## 6758                                      0.2463483
## 8674                                      0.2746866
## 15670                                     0.3733489
## 16697                                     0.3891503
## 18772                                     0.4233920
## 22453                                     0.4818809
##       .rownames EmploymentStatus.fctr
## 29121      9666              Employed
## 29122    113105    Not.in.Labor.Force
## 29123     13047              Disabled
## 29124     95473    Not.in.Labor.Force
## 29125      7506               Retired
## 29126     77820    Not.in.Labor.Force
##       EmploymentStatus.fctr.All.X..rcv.glmnet
## 29121                      Not.in.Labor.Force
## 29122                                    <NA>
## 29123                                Disabled
## 29124                                Employed
## 29125                                    <NA>
## 29126                                    <NA>
##       EmploymentStatus.fctr.All.X..rcv.glmnet.prob
## 29121                                    0.2824539
## 29122                                           NA
## 29123                                    0.3127349
## 29124                                    0.2924985
## 29125                                           NA
## 29126                                           NA
##       EmploymentStatus.fctr.All.X..rcv.glmnet.err
## 29121                                        TRUE
## 29122                                          NA
## 29123                                       FALSE
## 29124                                        TRUE
## 29125                                          NA
## 29126                                          NA
##       EmploymentStatus.fctr.All.X..rcv.glmnet.err.abs
## 29121                                       0.2745356
## 29122                                              NA
## 29123                                       0.0000000
## 29124                                       0.2044541
## 29125                                              NA
## 29126                                              NA
##       EmploymentStatus.fctr.All.X..rcv.glmnet.is.acc
## 29121                                          FALSE
## 29122                                             NA
## 29123                                           TRUE
## 29124                                          FALSE
## 29125                                             NA
## 29126                                             NA
##       EmploymentStatus.fctr.Final..rcv.glmnet
## 29121                      Not.in.Labor.Force
## 29122                                Employed
## 29123                      Not.in.Labor.Force
## 29124                                Employed
## 29125                                Employed
## 29126                                Employed
##       EmploymentStatus.fctr.Final..rcv.glmnet.prob
## 29121                                    0.2942089
## 29122                                    0.2941387
## 29123                                    0.2940581
## 29124                                    0.2936619
## 29125                                    0.2749707
## 29126                                    0.2732929
##       EmploymentStatus.fctr.Final..rcv.glmnet.err
## 29121                                        TRUE
## 29122                                        TRUE
## 29123                                        TRUE
## 29124                                        TRUE
## 29125                                        TRUE
## 29126                                        TRUE
##       EmploymentStatus.fctr.Final..rcv.glmnet.err.abs
## 29121                                       0.2826697
## 29122                                       0.2918380
## 29123                                       0.2932583
## 29124                                       0.1869001
## 29125                                       0.2590398
## 29126                                       0.1962120
##       EmploymentStatus.fctr.Final..rcv.glmnet.is.acc
## 29121                                          FALSE
## 29122                                          FALSE
## 29123                                          FALSE
## 29124                                          FALSE
## 29125                                          FALSE
## 29126                                          FALSE
##       EmploymentStatus.fctr.Final..rcv.glmnet.accurate
## 29121                                            FALSE
## 29122                                            FALSE
## 29123                                            FALSE
## 29124                                            FALSE
## 29125                                            FALSE
## 29126                                            FALSE
##       EmploymentStatus.fctr.Final..rcv.glmnet.error
## 29121                                     0.7057911
## 29122                                     0.7058613
## 29123                                     0.7059419
## 29124                                     0.7063381
## 29125                                     0.7250293
## 29126                                     0.7267071

dsp_feats_vctr <- c(NULL)
for(var in grep(".imp", names(glb_feats_df), fixed=TRUE, value=TRUE))
    dsp_feats_vctr <- union(dsp_feats_vctr, 
                            glb_feats_df[!is.na(glb_feats_df[, var]), "id"])

# print(glbObsTrn[glbObsTrn$UniqueID %in% FN_OOB_ids, 
#                     grep(glb_rsp_var, names(glbObsTrn), value=TRUE)])

print(setdiff(names(glbObsTrn), names(glbObsAll)))
## [1] "EmploymentStatus.fctr.Final..rcv.glmnet"        
## [2] "EmploymentStatus.fctr.Final..rcv.glmnet.prob"   
## [3] "EmploymentStatus.fctr.Final..rcv.glmnet.err"    
## [4] "EmploymentStatus.fctr.Final..rcv.glmnet.err.abs"
## [5] "EmploymentStatus.fctr.Final..rcv.glmnet.is.acc"
for (col in setdiff(names(glbObsTrn), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.src == "Train", col] <- glbObsTrn[, col]

print(setdiff(names(glbObsFit), names(glbObsAll)))
## character(0)
print(setdiff(names(glbObsOOB), names(glbObsAll)))
## character(0)
for (col in setdiff(names(glbObsOOB), names(glbObsAll)))
    # Merge or cbind ?
    glbObsAll[glbObsAll$.lcn == "OOB", col] <- glbObsOOB[, col]
    
print(setdiff(names(glbObsNew), names(glbObsAll)))
## character(0)
#glb2Sav(); all.equal(savObsAll, glbObsAll); all.equal(sav_models_lst, glb_models_lst)
#load(file = paste0(glbOut$pfx, "dsk_knitr.RData"))
#cmpCols <- names(glbObsAll)[!grepl("\\.Final\\.", names(glbObsAll))]; all.equal(savObsAll[, cmpCols], glbObsAll[, cmpCols]); all.equal(savObsAll[, "H.P.http"], glbObsAll[, "H.P.http"]); 

replay.petrisim(pn = glb_analytics_pn, 
    replay.trans = (glb_analytics_avl_objs <- c(glb_analytics_avl_objs, 
        "data.training.all.prediction","model.final")), flip_coord = TRUE)
## time trans    "bgn " "fit.data.training.all " "predict.data.new " "end " 
## 0.0000   multiple enabled transitions:  data.training.all data.new model.selected    firing:  data.training.all 
## 1.0000    1   2 1 0 0 
## 1.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction   firing:  data.new 
## 2.0000    2   1 1 1 0 
## 2.0000   multiple enabled transitions:  data.training.all data.new model.selected model.final data.training.all.prediction data.new.prediction   firing:  model.selected 
## 3.0000    3   0 2 1 0 
## 3.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  data.training.all.prediction 
## 4.0000    5   0 1 1 1 
## 4.0000   multiple enabled transitions:  model.final data.training.all.prediction data.new.prediction     firing:  model.final 
## 5.0000    4   0 0 2 1

glb_chunks_df <- myadd_chunk(glb_chunks_df, "predict.data.new", major.inc = TRUE)
##                label step_major step_minor label_minor      bgn      end
## 21 fit.data.training          9          1           1 2972.312 3052.423
## 22  predict.data.new         10          0           0 3052.423       NA
##    elapsed
## 21  80.111
## 22      NA

Step 10.0: predict data new

## Warning in glb_analytics_diag_plots(obs_df = glbObsNew, mdl_id =
## glb_fin_mdl_id, : Limiting important feature scatter plots to 5 out of 10
## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## Warning: Removed 25789 rows containing missing values (geom_point).

## NULL
## Loading required package: tidyr
## 
## Attaching package: 'tidyr'
## The following object is masked from 'package:Matrix':
## 
##     expand
## [1] "OOBobs total range outliers: 0"
## [1] "newobs EmploymentStatus.fctr.Final..rcv.glmnet Employed: min < min of Train range: 24451"
##    .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 2      91211                                Employed  11
## 16     92332                                Employed   8
## 27     92480                                Employed   6
## 33     92056                                Employed   0
## 42     91863                                Employed   7
## 47     93035                                Employed   1
##       .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 11326     39860                                Employed   2
## 22350     81743                                Employed  10
## 39062     12105                                Employed  12
## 50138     83384                                Employed  14
## 55093     56439                                Employed   8
## 97641     70549                                Employed   0
##        .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 131249     27532                                Employed   4
## 131253     53684                                Employed   5
## 131261     32548                                Employed   2
## 131266    109385                                Employed  13
## 131286     53685                                Employed   6
## 131288     81739                                Employed  14
##      id    cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## Age Age 0.279553           FALSE  0.279553         NA  1.089125
##     percentUnique zeroVar   nzv is.cor.y.abs.low interaction.feat
## Age    0.06349928   FALSE FALSE            FALSE               NA
##     shapiro.test.p.value rsp_var_raw rsp_var max min
## Age         1.847733e-31       FALSE      NA  85   0
##     max.EmploymentStatus.fctr.Disabled max.EmploymentStatus.fctr.Employed
## Age                                 85                                 85
##     max.EmploymentStatus.fctr.Not.in.Labor.Force
## Age                                           85
##     max.EmploymentStatus.fctr.Retired max.EmploymentStatus.fctr.Unemployed
## Age                                85                                   85
##     min.EmploymentStatus.fctr.Disabled min.EmploymentStatus.fctr.Employed
## Age                                 15                                 15
##     min.EmploymentStatus.fctr.Not.in.Labor.Force
## Age                                           15
##     min.EmploymentStatus.fctr.Retired min.EmploymentStatus.fctr.Unemployed
## Age                                16                                   15
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Disabled
## Age                                                   71
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Employed
## Age                                                   74
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Not.in.Labor.Force
## Age                                                             61
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Retired
## Age                                                  85
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Disabled
## Age                                                   43
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Employed
## Age                                                   15
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Not.in.Labor.Force
## Age                                                             15
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Retired
## Age                                                  60
##     max.EmploymentStatus.fctr.Final..rcv.glmnet.Employed
## Age                                                   61
##     max.EmploymentStatus.fctr.Final..rcv.glmnet.Not.in.Labor.Force
## Age                                                             21
##     min.EmploymentStatus.fctr.Final..rcv.glmnet.Employed
## Age                                                    0
##     min.EmploymentStatus.fctr.Final..rcv.glmnet.Not.in.Labor.Force
## Age                                                              0
## [1] "newobs EmploymentStatus.fctr.Final..rcv.glmnet Not.in.Labor.Force: min < min of Train range: 887"
##     .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 100     34795                      Not.in.Labor.Force   7
## 102     34793                      Not.in.Labor.Force   6
## 145     35046                      Not.in.Labor.Force   5
## 197     34794                      Not.in.Labor.Force   6
## 254     84130                      Not.in.Labor.Force   3
## 457     80243                      Not.in.Labor.Force   5
##       .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 14587     91687                      Not.in.Labor.Force   2
## 24610     80751                      Not.in.Labor.Force   2
## 27281    101185                      Not.in.Labor.Force   4
## 52743     82549                      Not.in.Labor.Force   6
## 73751      6656                      Not.in.Labor.Force  12
## 87070    115279                      Not.in.Labor.Force   9
##        .rownames EmploymentStatus.fctr.Final..rcv.glmnet Age
## 131022     51446                      Not.in.Labor.Force   7
## 131067     81761                      Not.in.Labor.Force   9
## 131078     81760                      Not.in.Labor.Force   6
## 131093     81762                      Not.in.Labor.Force  12
## 131148    118082                      Not.in.Labor.Force   1
## 131298     37126                      Not.in.Labor.Force   4
##      id    cor.y exclude.as.feat cor.y.abs cor.high.X freqRatio
## Age Age 0.279553           FALSE  0.279553         NA  1.089125
##     percentUnique zeroVar   nzv is.cor.y.abs.low interaction.feat
## Age    0.06349928   FALSE FALSE            FALSE               NA
##     shapiro.test.p.value rsp_var_raw rsp_var max min
## Age         1.847733e-31       FALSE      NA  85   0
##     max.EmploymentStatus.fctr.Disabled max.EmploymentStatus.fctr.Employed
## Age                                 85                                 85
##     max.EmploymentStatus.fctr.Not.in.Labor.Force
## Age                                           85
##     max.EmploymentStatus.fctr.Retired max.EmploymentStatus.fctr.Unemployed
## Age                                85                                   85
##     min.EmploymentStatus.fctr.Disabled min.EmploymentStatus.fctr.Employed
## Age                                 15                                 15
##     min.EmploymentStatus.fctr.Not.in.Labor.Force
## Age                                           15
##     min.EmploymentStatus.fctr.Retired min.EmploymentStatus.fctr.Unemployed
## Age                                16                                   15
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Disabled
## Age                                                   71
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Employed
## Age                                                   74
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Not.in.Labor.Force
## Age                                                             61
##     max.EmploymentStatus.fctr.All.X..rcv.glmnet.Retired
## Age                                                  85
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Disabled
## Age                                                   43
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Employed
## Age                                                   15
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Not.in.Labor.Force
## Age                                                             15
##     min.EmploymentStatus.fctr.All.X..rcv.glmnet.Retired
## Age                                                  60
##     max.EmploymentStatus.fctr.Final..rcv.glmnet.Employed
## Age                                                   61
##     max.EmploymentStatus.fctr.Final..rcv.glmnet.Not.in.Labor.Force
## Age                                                             21
##     min.EmploymentStatus.fctr.Final..rcv.glmnet.Employed
## Age                                                    0
##     min.EmploymentStatus.fctr.Final..rcv.glmnet.Not.in.Labor.Force
## Age                                                              0
## [1] "newobs total range outliers: 25338"
## [1] TRUE
## [1] "glb_sel_mdl_id: All.X##rcv#glmnet"
## [1] "glb_fin_mdl_id: Final##rcv#glmnet"
## [1] "Cross Validation issues:"
##        MFO###myMFO_classfr  Random###myrandom_classfr 
##                          0                          0 
## Max.cor.Y.rcv.1X1###glmnet 
##                          0
##                            max.Accuracy.OOB max.Kappa.OOB
## Max.cor.Y##rcv#rpart              0.7276701  0.4783438508
## All.X##rcv#glmnet                 0.7229115  0.4729121383
## Max.cor.Y.rcv.1X1###glmnet        0.6859711  0.3481272164
## MFO###myMFO_classfr               0.5850546  0.0000000000
## Random###myrandom_classfr         0.3991540  0.0006568311
## Final##rcv#glmnet                        NA            NA
## [1] "All.X##rcv#glmnet OOB confusion matrix & accuracy: "
##                     Prediction
## Reference            Disabled Employed Not.in.Labor.Force Retired
##   Disabled                 82     1169                 70     215
##   Employed                 50    15141                614     793
##   Not.in.Labor.Force       17     2429               1545     108
##   Retired                  26     1234                  5    3741
##   Unemployed                6      948                150      27
##                     Prediction
## Reference            Unemployed
##   Disabled                    0
##   Employed                    0
##   Not.in.Labor.Force          0
##   Retired                     0
##   Unemployed                  0
##        err.abs.fit.sum err.abs.OOB.sum err.abs.trn.sum err.abs.new.sum
## .dummy        3967.069        1481.543        5451.929              NA
##        .freqRatio.Fit .freqRatio.OOB .freqRatio.Tst .n.Fit .n.New.Employed
## .dummy              1              1              1  77143           24900
##        .n.New.Not.in.Labor.Force .n.OOB .n.Trn.Disabled .n.Trn.Employed
## .dummy                       889  28370            5712           61733
##        .n.Trn.Not.in.Labor.Force .n.Trn.Retired .n.Trn.Unemployed .n.Tst
## .dummy                     15246          18619              4203  25789
##        .n.fit .n.new .n.trn err.abs.OOB.mean err.abs.fit.mean
## .dummy  77143  25789 105513       0.05222217       0.05142488
##        err.abs.new.mean err.abs.trn.mean
## .dummy               NA       0.05167068
##           err.abs.fit.sum           err.abs.OOB.sum 
##              3.967069e+03              1.481543e+03 
##           err.abs.trn.sum           err.abs.new.sum 
##              5.451929e+03                        NA 
##            .freqRatio.Fit            .freqRatio.OOB 
##              1.000000e+00              1.000000e+00 
##            .freqRatio.Tst                    .n.Fit 
##              1.000000e+00              7.714300e+04 
##           .n.New.Employed .n.New.Not.in.Labor.Force 
##              2.490000e+04              8.890000e+02 
##                    .n.OOB           .n.Trn.Disabled 
##              2.837000e+04              5.712000e+03 
##           .n.Trn.Employed .n.Trn.Not.in.Labor.Force 
##              6.173300e+04              1.524600e+04 
##            .n.Trn.Retired         .n.Trn.Unemployed 
##              1.861900e+04              4.203000e+03 
##                    .n.Tst                    .n.fit 
##              2.578900e+04              7.714300e+04 
##                    .n.new                    .n.trn 
##              2.578900e+04              1.055130e+05 
##          err.abs.OOB.mean          err.abs.fit.mean 
##              5.222217e-02              5.142488e-02 
##          err.abs.new.mean          err.abs.trn.mean 
##                        NA              5.167068e-02
## [1] "Features Importance for selected models:"
##                                       All.X..rcv.glmnet.imp.Disabled
## Education.fctrNo high school diploma                     100.0000000
## Married.fctrMarried                                       80.5845919
## Education.fctrMaster's degree                             81.6105115
## Citizenship.fctrNon-Citizen                               80.8187616
## Education.fctrDoctorate degree                            58.8506019
## Education.fctrProfessional degree                         71.1360427
## Married.fctrWidowed                                        0.0000000
## Sex.fctrMale                                               0.0000000
## Race.fctrBlack                                            29.1551897
## Education.fctrHigh school                                 34.0699104
## Education.fctrBachelor's degree                           59.1559838
## Citizenship.fctrCitizen, Naturalized                      47.4802548
## Race.fctrAmerican Indian                                   0.8471631
## Race.fctrAsian                                             6.8442014
## Married.fctrNever Married                                  0.0000000
## Education.fctrSome college, no degree                     10.8622226
##                                       All.X..rcv.glmnet.imp.Employed
## Education.fctrNo high school diploma                       80.094677
## Married.fctrMarried                                         0.000000
## Education.fctrMaster's degree                              24.226282
## Citizenship.fctrNon-Citizen                                 7.227984
## Education.fctrDoctorate degree                             72.186222
## Education.fctrProfessional degree                          50.306390
## Married.fctrWidowed                                        11.058165
## Sex.fctrMale                                               20.843611
## Race.fctrBlack                                             19.032460
## Education.fctrHigh school                                  42.836408
## Education.fctrBachelor's degree                            14.350902
## Citizenship.fctrCitizen, Naturalized                        7.787895
## Race.fctrAmerican Indian                                   34.669462
## Race.fctrAsian                                              0.000000
## Married.fctrNever Married                                  19.383808
## Education.fctrSome college, no degree                      20.401790
##                                       All.X..rcv.glmnet.imp.Not.in.Labor.Force
## Education.fctrNo high school diploma                                 90.911477
## Married.fctrMarried                                                  24.377008
## Education.fctrMaster's degree                                         3.826702
## Citizenship.fctrNon-Citizen                                          14.922307
## Education.fctrDoctorate degree                                        0.000000
## Education.fctrProfessional degree                                     0.000000
## Married.fctrWidowed                                                  54.767522
## Sex.fctrMale                                                         67.291846
## Race.fctrBlack                                                        8.553671
## Education.fctrHigh school                                             0.000000
## Education.fctrBachelor's degree                                       0.000000
## Citizenship.fctrCitizen, Naturalized                                  3.886102
## Race.fctrAmerican Indian                                              0.000000
## Race.fctrAsian                                                       41.270984
## Married.fctrNever Married                                            31.347716
## Education.fctrSome college, no degree                                21.607572
##                                       All.X..rcv.glmnet.imp.Retired
## Education.fctrNo high school diploma                       0.000000
## Married.fctrMarried                                       38.363589
## Education.fctrMaster's degree                             22.158309
## Citizenship.fctrNon-Citizen                               27.377846
## Education.fctrDoctorate degree                             3.271762
## Education.fctrProfessional degree                          0.000000
## Married.fctrWidowed                                       49.553115
## Sex.fctrMale                                              10.528453
## Race.fctrBlack                                             0.000000
## Education.fctrHigh school                                  7.143373
## Education.fctrBachelor's degree                            3.867177
## Citizenship.fctrCitizen, Naturalized                      19.780937
## Race.fctrAmerican Indian                                  16.946844
## Race.fctrAsian                                            14.009402
## Married.fctrNever Married                                  4.632821
## Education.fctrSome college, no degree                      0.000000
##                                       All.X..rcv.glmnet.imp.Unemployed
## Education.fctrNo high school diploma                        11.0521930
## Married.fctrMarried                                         50.7011130
## Education.fctrMaster's degree                                0.0000000
## Citizenship.fctrNon-Citizen                                  0.0000000
## Education.fctrDoctorate degree                               0.0000000
## Education.fctrProfessional degree                            0.0000000
## Married.fctrWidowed                                         10.6888708
## Sex.fctrMale                                                21.5884246
## Race.fctrBlack                                              46.9542665
## Education.fctrHigh school                                    0.5911445
## Education.fctrBachelor's degree                              0.0000000
## Citizenship.fctrCitizen, Naturalized                         0.0000000
## Race.fctrAmerican Indian                                    21.2926566
## Race.fctrAsian                                               5.1886845
## Married.fctrNever Married                                    2.4655739
## Education.fctrSome college, no degree                        0.3188346
##                                       Final..rcv.glmnet.imp.Disabled
## Education.fctrNo high school diploma                      100.000000
## Married.fctrMarried                                        81.246159
## Education.fctrMaster's degree                              79.951444
## Citizenship.fctrNon-Citizen                                80.712770
## Education.fctrDoctorate degree                             55.015897
## Education.fctrProfessional degree                          78.558535
## Married.fctrWidowed                                         0.000000
## Sex.fctrMale                                                0.000000
## Race.fctrBlack                                             32.851713
## Education.fctrHigh school                                  33.098847
## Education.fctrBachelor's degree                            63.921032
## Citizenship.fctrCitizen, Naturalized                       46.351000
## Race.fctrAmerican Indian                                    5.675508
## Race.fctrAsian                                              5.460627
## Married.fctrNever Married                                   0.000000
## Education.fctrSome college, no degree                       4.114656
##                                       Final..rcv.glmnet.imp.Employed
## Education.fctrNo high school diploma                       77.628938
## Married.fctrMarried                                         0.000000
## Education.fctrMaster's degree                              28.313848
## Citizenship.fctrNon-Citizen                                10.051168
## Education.fctrDoctorate degree                             69.723991
## Education.fctrProfessional degree                          55.506180
## Married.fctrWidowed                                         4.423530
## Sex.fctrMale                                               20.302323
## Race.fctrBlack                                             15.477478
## Education.fctrHigh school                                  40.875713
## Education.fctrBachelor's degree                            14.181781
## Citizenship.fctrCitizen, Naturalized                        6.892279
## Race.fctrAmerican Indian                                   28.796180
## Race.fctrAsian                                              0.000000
## Married.fctrNever Married                                  18.771361
## Education.fctrSome college, no degree                      19.314050
##                                       Final..rcv.glmnet.imp.Not.in.Labor.Force
## Education.fctrNo high school diploma                                92.4379866
## Married.fctrMarried                                                 22.9633810
## Education.fctrMaster's degree                                        3.4239386
## Citizenship.fctrNon-Citizen                                         15.9235833
## Education.fctrDoctorate degree                                       0.0000000
## Education.fctrProfessional degree                                    0.0000000
## Married.fctrWidowed                                                 63.0646928
## Sex.fctrMale                                                        69.2621101
## Race.fctrBlack                                                       4.3252103
## Education.fctrHigh school                                            0.6234842
## Education.fctrBachelor's degree                                      0.0000000
## Citizenship.fctrCitizen, Naturalized                                 0.0000000
## Race.fctrAmerican Indian                                             0.0000000
## Race.fctrAsian                                                      41.7507091
## Married.fctrNever Married                                           30.7054464
## Education.fctrSome college, no degree                               24.0160296
##                                       Final..rcv.glmnet.imp.Retired
## Education.fctrNo high school diploma                       0.000000
## Married.fctrMarried                                       34.830347
## Education.fctrMaster's degree                             24.998385
## Citizenship.fctrNon-Citizen                               27.065976
## Education.fctrDoctorate degree                             0.000000
## Education.fctrProfessional degree                          0.000000
## Married.fctrWidowed                                       51.037204
## Sex.fctrMale                                               9.656200
## Race.fctrBlack                                             0.000000
## Education.fctrHigh school                                  6.241790
## Education.fctrBachelor's degree                            7.772573
## Citizenship.fctrCitizen, Naturalized                      20.694932
## Race.fctrAmerican Indian                                   2.938171
## Race.fctrAsian                                            12.944049
## Married.fctrNever Married                                  6.981007
## Education.fctrSome college, no degree                      0.000000
##                                       Final..rcv.glmnet.imp.Unemployed
## Education.fctrNo high school diploma                          8.457547
## Married.fctrMarried                                          53.574303
## Education.fctrMaster's degree                                 0.000000
## Citizenship.fctrNon-Citizen                                   0.000000
## Education.fctrDoctorate degree                                0.000000
## Education.fctrProfessional degree                             0.000000
## Married.fctrWidowed                                           5.258252
## Sex.fctrMale                                                 15.977102
## Race.fctrBlack                                               49.959778
## Education.fctrHigh school                                     0.000000
## Education.fctrBachelor's degree                               0.000000
## Citizenship.fctrCitizen, Naturalized                          0.000000
## Race.fctrAmerican Indian                                     35.242184
## Race.fctrAsian                                                0.000000
## Married.fctrNever Married                                     0.501794
## Education.fctrSome college, no degree                         0.000000
##                                       imp.mean
## Education.fctrNo high school diploma  56.05828
## Married.fctrMarried                   38.66405
## Education.fctrMaster's degree         26.85094
## Citizenship.fctrNon-Citizen           26.41004
## Education.fctrDoctorate degree        25.90485
## Education.fctrProfessional degree     25.55071
## Married.fctrWidowed                   24.98514
## Sex.fctrMale                          23.54501
## Race.fctrBlack                        20.63098
## Education.fctrHigh school             16.54807
## Education.fctrBachelor's degree       16.32494
## Citizenship.fctrCitizen, Naturalized  15.28734
## Race.fctrAmerican Indian              14.64082
## Race.fctrAsian                        12.74687
## Married.fctrNever Married             11.47895
## Education.fctrSome college, no degree 10.06352
## [1] "glbObsNew prediction stats:"
## 
##           Disabled           Employed Not.in.Labor.Force 
##                  0              24900                889 
##            Retired         Unemployed 
##                  0                  0
##                   label step_major step_minor label_minor      bgn
## 22     predict.data.new         10          0           0 3052.423
## 23 display.session.info         11          0           0 3134.169
##         end elapsed
## 22 3134.168  81.746
## 23       NA      NA

Null Hypothesis (\(\sf{H_{0}}\)): mpg is not impacted by am_fctr.
The variance by am_fctr appears to be independent. #{r q1, cache=FALSE} # print(t.test(subset(cars_df, am_fctr == "automatic")$mpg, # subset(cars_df, am_fctr == "manual")$mpg, # var.equal=FALSE)$conf) # We reject the null hypothesis i.e. we have evidence to conclude that am_fctr impacts mpg (95% confidence). Manual transmission is better for miles per gallon versus automatic transmission.

##                        label step_major step_minor label_minor      bgn
## 20         fit.data.training          9          0           0 1331.743
## 17                fit.models          8          1           1  153.030
## 22          predict.data.new         10          0           0 3052.423
## 21         fit.data.training          9          1           1 2972.312
## 2               inspect.data          2          0           0   30.031
## 16                fit.models          8          0           0  118.503
## 18                fit.models          8          2           2 1278.196
## 19                fit.models          8          3           3 1310.740
## 1                import.data          1          0           0    9.784
## 4             transform.data          2          2           2   78.514
## 15           select.features          7          0           0  107.383
## 14   partition.data.training          6          0           0  101.177
## 5           extract.features          3          0           0   92.220
## 3                 scrub.data          2          1           1   73.211
## 12       manage.missing.data          4          0           0   99.484
## 11      extract.features.end          3          6           6   98.568
## 13              cluster.data          5          0           0  100.642
## 10   extract.features.string          3          5           5   98.220
## 7     extract.features.image          3          2           2   98.062
## 9      extract.features.text          3          4           4   98.168
## 8     extract.features.price          3          3           3   98.129
## 6  extract.features.datetime          3          1           1   98.024
##         end  elapsed duration
## 20 2972.311 1640.568 1640.568
## 17 1278.195 1125.166 1125.165
## 22 3134.168   81.746   81.745
## 21 3052.423   80.111   80.111
## 2    73.211   43.180   43.180
## 16  153.030   34.527   34.527
## 18 1310.739   32.544   32.543
## 19 1331.742   21.002   21.002
## 1    30.030   20.246   20.246
## 4    92.220   13.706   13.706
## 15  118.503   11.120   11.120
## 14  107.382    6.206    6.205
## 5    98.023    5.804    5.803
## 3    78.514    5.303    5.303
## 12  100.641    1.157    1.157
## 11   99.484    0.916    0.916
## 13  101.177    0.535    0.535
## 10   98.567    0.347    0.347
## 7    98.129    0.067    0.067
## 9    98.219    0.052    0.051
## 8    98.167    0.038    0.038
## 6    98.061    0.038    0.037
## [1] "Total Elapsed Time: 3,134.168 secs"